lockstock
lockstock

Reputation: 2437

Matching Id with that of an object in an array

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

Answers (2)

Muad'Dib
Muad'Dib

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

Related Questions