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>();
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With