Search code examples
c#classilist

Returning an instance of a class from IList<t>


I would like to return the class Animal from foo. However, I would like to do so in a proper way so that future implementations of the code are easy to make. In other words, I do not want to use Obj.FirstOrDefault(). here is the code

  static void Main(string[] args)
    {
        Program Pro = new Program();
        Animal Cat = Pro.foo();
        Console.WriteLine(Cat.Name);
        Console.ReadKey();
    }

    public Animal foo()
    {
        IList<Animal> Obj = new List<Animal>() { new Animal { Name = "Bob", ID = 1 } };
        Animal result = Obj.FirstOrDefault(); 
        return result;
    }
}
class Animal
{
    public string Name { get; set; }
    public int ID { get; set; }
}

Solution

  • There is no way to return Animal without FirstOrDefault(). You could prefix FirstOrDefault() with .Where(a => a.CatName = "Fido")