Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graceful way to handle item not found in a collection in C#

Tags:

c#

I have the following scenario:

  1. I have a foreach loop that loops through a collection, if an item is found (based on criteria as in example below), it will return that item.

If not what is the most graceful way to deal with this exception. I have a throw new notimplementedexception but I think there is a more elegant way.

Code is:

 foreach (SPContentType type in sPContentTypeCollection)
            {
                if (type.Name == contentTypeName)
                {
                    return type; 
                }
            }

 throw new NotImplementedException(); 

As you can see, it's not what I would call readable code. How can I make it easier for the next guy to maintain. On a side note, it does what it should from a technical perspective.

like image 511
JL. Avatar asked Apr 04 '11 16:04

JL.


2 Answers

Well NotImplementedException is certainly inappropriate, because you have implemented the method... but what sort of exception should you throw? It really depends on the context, to be honest.

Sometimes it would be appropriate to return null to indicate a missing value. Other times, throwing an exception is fine - possibly an InvalidOperationException for example. You should throw an exception if this situation represents an error of some description, rather than it being a perfectly reasonable situation which the caller should expect to occur.

As for the rest of the code... if you're using .NET 3.5 you could just use LINQ:

return sPContentTypeCollection.Cast<SPContentType>()
                              .First(type => type.Name == contentTypeName);

That will throw an InvalidOperationException for you automatically if the name isn't found. Or if you want to return null:

// type shortened to t to avoid scrollbars...
return sPContentTypeCollection.Cast<SPContentType>()
                              .FirstOrDefault(t => t.Name == contentTypeName);
like image 197
Jon Skeet Avatar answered Nov 18 '22 13:11

Jon Skeet


It really depends on whether this is an expected or exceptional case.

If the item you compare with is passed to a method and there really always should be a matching item in the collection I'd throw an ArgumentOutOfRangeException exception.

If it is expected that sometimes no matching item is found, I would just return null to indicate that the requested item was not found.

like image 4
BrokenGlass Avatar answered Nov 18 '22 12:11

BrokenGlass