Linked Questions

Popular Questions

Though, the below question seems to be silly, but still it would help others also. I have method that return a list.And the method return type IEnumnerable. Method:

public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public static IEnumerable<Person> GetPersons()
        {
            List<Person> personList = new List<Person>()
                                          {
                                              new Person() { Age = 10, Name = "Vijay"}
                                          };

           return personList;

        }
    }

Now whenever I am calling this method and checking the type.The output is

System.Collections.Generic.List

Since it is a List. I should be able add Items to the list. But system is throwing a compilation error. Below is the execution part:

public class Program
    {
        public static void Main(string[] ar)
        {
            var personList = Person.GetPersons();
            Console.WriteLine(personList.GetType()); //System.Collections.Generic.List
            personList.Add(new Person(){Age = 11, Name = "Ajay"}); // Compilation error
            Console.ReadKey();

        }
    }

So could anyone help me with the understanding. It would be great help. Thanks in advance.

Related Questions