Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C# generics affect collections with primitives

As I understand it, C#/.Net generics support some degree of reification. So, if I have the following code:

List<int> list = new List<int>();
list.Add(1);

Will the value 1 be autoboxed or will the 'list' object handle primitive ints efficiently?

like image 971
Michael Barker Avatar asked Sep 18 '10 10:09

Michael Barker


People also ask

How does C operate?

c is called the source file which keeps the code of the program. Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no error, then it stores the file as a . obj file of the same name, called the object file.

How does or work in C?

The result of a logical OR ( || operator in C) is true if EITHER of its inputs is true. Similarly logical AND ( && operator in C) is true if BOTH of its inputs are true. (Note that 0 is FALSE and anything else is TRUE, 1 is conventionally used in truth tables like the above).

What is -= in C?

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.


2 Answers

No, it won't be boxed. At execution time, the backing array for the List<int> will genuinely be an int[]. Note that this isn't just the case with genuine primitive types - List<T> won't box values of any value type (assuming it's been declared as List<Guid> etc rather than List<object>).

Basically, generics in .NET keep a lot more of their information than they do in Java - the CLR natively understands generics and deals with them appropriately, rather than in Java where the JVM is pretty much ignorant of them.

For example, if you write:

object list = new List<string>();
Type type = list.GetType();

Then type will be equal to typeof(List<string>) - which is then different to (say) List<Guid> etc.

like image 131
Jon Skeet Avatar answered Oct 03 '22 09:10

Jon Skeet


The int values will not be boxed within the list. This is one of the beauties with generics, that the compiler (more specifically the JIT-compiler, I believe) will construct a typed version of the List<> class, rather than storing the values as object. So it does not only enforce type safety through the exposed methods and properties, but it is genuinely typed in all aspects.

like image 22
Fredrik Mörk Avatar answered Oct 03 '22 09:10

Fredrik Mörk