To simplify, let's say I have a method that should return a User object from an ID found in a list of users. If no user is found I want to throw an Exception.
My current code works:
public User GetUserFromID(int id)
{
foreach (User u in Users)
if (u.id == id)
return u;
throw new Exception("No user is found");
}
But my problem comes when I want to find a user with a lambda expression instead of the foreach loop. The following code succeeds in returning the correct User object but never throws an exception if nothing is found.
public User GetUserFromID(int id)
{
return Users.Find(u => u.id == id);
throw new Exception("No user is found");
}