Using IEnumerable and GetEnumerator

  • Thread starter Thread starter Magnus.Moraberg
  • Start date Start date
M

Magnus.Moraberg

Hi,

I have the following class snippet -

public class ResultsForTestCases : IEnumerable
{
public int Length
{
get { return resultsForTestCases.Length; }
}

IEnumerator IEnumerable.GetEnumerator() { return
resultsForTestCases.GetEnumerator(); }
ResultsForTestCase[] resultsForTestCases;
}

The problem though is if resultsForTestCases is null, then
resultsForTestCases.GetEnumerator() and indeed Length will fail. How
should I handle this.

Thanks,

Barry
 
Well, what do you want it to do? Personally, I suspect the simplest
option is to default the array to an empty array, perhaps one shared
by all instances (to avoid lots of zero-length arrays):

static readonly ResultsForTestCase[] EmptyCases = new
ResultsForTestCase[0];
ResultsForTestCase[] resultsForTestCases = EmptyCases;

Otherwise, you have to check for null and return 0 (for length) and
perhaps an empty enumerator (such as EmptyCases.GetEnumerator()) if it
is null.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top