Reputation: 2437
what is a better way of implementing this pattern?:
void ValidateId(int Id, MyObject[] objects)
{
foreach (var myObject in objects)
{
if (Id == myObject.Id){
return;
}
}
throw new Exception("Invalid Id");
}
Upvotes: 0
Views: 72
Reputation: 29256
first, I would not throw an exception unless the situation is exceptional. Rather, prefer to return a bool and handle a return value of false with a nice friendly error message.
as for validating, you can use Linq....
bool ValidateId(int Id, MyObject[] objects)
{
return objects.Any( o=>o.Id == Id );
}
Upvotes: 3
Reputation: 19684
Use Contains()
http://www.dotnettoad.com/index.php?/archives/10-Array.Contains.html
Upvotes: 0