C # concepts: what is the “LIST” keyword?

I am doing a C # OOP crash course and am curious to know what the LIST keyword is in the code below:

var actors = new List<Actor>(); 
+4
source share
4 answers

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

A container simply stores things, it does not need to know what it stores. We could implement 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 do not have type safety. I could abuse the hell from this collection as follows:

 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 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 executed.

 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 this helps. Sorry if I made any syntax errors there, my C # is rusty;)

+8
source

This is not a keyword, this is a class identifier.

+5
source

List <Actor> () describes a list of Actor objects. Typically, a list is a collection of objects that are sorted in some way and can be accessed by index.

+2
source

This is not a general OO concept. This is a type of .NET library. I would suggest picking up a good C # and .NET book .

0
source

Source: https://habr.com/ru/post/1300018/


All Articles