0

I am looking at the following code example:

// Student collection
IList<Student> studentList = new List<Student>() { 
        new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
        new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
        new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
        new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
        new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } 
    };

// LINQ Method Syntax to find out teenager students
var teenAgerStudents = studentList.Where(s => s.Age > 12 && s.Age < 20)
                                  .ToList<Student>();

The .ToList<Student>() could also be written as .ToList();

What is the purpose of giving the class name in the ToList<ClassName>?

variable
  • 8,262
  • 9
  • 95
  • 215
  • 2
    Either way you will end up calling the extension method `Enumerable.ToList`, but the compiler will infer the generic parameter if you leave it out, since in this case the result is unambiguous. (see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods) – Jeremy Lakeman Jun 28 '22 at 04:49
  • 2
    It's actually answered here - https://stackoverflow.com/questions/33544078/tolistt-vs-tolist In effect the generated code will always have the type inferred. – Melroy Coelho Jun 28 '22 at 04:52
  • To be much stricter. – shingo Jun 28 '22 at 04:53
  • There is answer of your question: [https://stackoverflow.com](https://stackoverflow.com/questions/52024534/difference-between-as-list-vs-tolist) – Davoud Ebrahimi Jun 28 '22 at 04:55

0 Answers0