Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Concepts: what the "LIST" keyword represents?

Tags:

c#

list

I have been doing a crash course of C# OOP and am curious to know what the "LIST" keyword represents in the code below:

var actors = new List<Actor>();
like image 547
LearningCSharp Avatar asked Dec 07 '22 04:12

LearningCSharp


1 Answers

List<T> is a class with a type parameter. This is called "generics" and allows you to manipulate objects opaquely within the class, especially useful for container classes like a list or a queue.

A container just stores things, it doesn't really need to know what it is storing. We could implement it like this without generics:

class List
{
    public List( ) { }
    public void Add( object toAdd ) { /*add 'toAdd' to an object array*/ }
    public void Remove( object toRemove ) { /*remove 'toRemove' from array*/ }
    public object operator []( int index ) { /*index into storage array and return value*/ }
}

However, we don't have type safety. I could abuse the hell out of that collection like this:

List list = new List( );
list.Add( 1 );
list.Add( "uh oh" );
list.Add( 2 );
int i = (int)list[1]; // boom goes the dynamite

Using generics in C# allows us to use these types of container classes in a type safe manner.

class List<T>
{
    // 'T' is our type.  We don't need to know what 'T' is,
    // we just need to know that it is a type.

    public void Add( T toAdd ) { /*same as above*/ }
    public void Remove( T toAdd ) { /*same as above*/ }
    public T operator []( int index ) { /*same as above*/ } 
}

Now if we try to add something that does not belong we get a compile time error, much preferable to an error that occurs when our program is executing.

List<int> list = new List<int>( );
list.Add( 1 );               // fine
list.Add( "not this time" ); // doesn't compile, you know there is a problem

Hope that helped. Sorry if I made any syntax errors in there, my C# is rusty ;)

like image 100
Ed S. Avatar answered Dec 10 '22 02:12

Ed S.