Home > Back-end >  What does List<"CLASSNAME"> "objectname" = new List<"CLASSNAME&quo
What does List<"CLASSNAME"> "objectname" = new List<"CLASSNAME&quo

Time:06-20

I know how to declare a simple generic list in C#, but I cant understand what does it mean when a CLASS is passed into the list. I mean aren't we supposed to pass the datatype into the list before we can add our elements into it? For example consider the following code

 class Program
{
    static void Main(string[] args)
    {
        List<Student> s1 = new List<Student>(); // What does this line mean? And How am I supposed to use this? 
        Console.WriteLine(s1);
        Console.ReadKey();
    }
}
 class Student
 {
    String name;
    int id;
 }

CodePudding user response:

List<Student> s1 = new List<Student>();

Means that your list s1 is a list of objects of type Student, and will never contain anything else. It is useful to type your list to limit runtime errors and have better code completion during development.

CodePudding user response:

This:

SomeType someVariable = new SomeType();

is shorthand for this:

SomeType someVariable;

someVariable = new SomeType();

It simply declares a variable of a type, creates an object of that type and assigns the object to the variable. That's exactly what this code is doing:

List<Student> s1 = new List<Student>();

You say that you know how to declare a generic list but that's what that code is doing, then creating a generic list of that type and assigning it to the declared variable.

As is always the case, you can then use the variable to access the assigned object. You can add, insert and remove items, enumerate the list or whatever you would usually do with a List<T>.

  •  Tags:  
  • c#
  • Related