Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do Value Types in .NET actually work?

Tags:

c#

I have a problem with understanding Value Types representation in .NET. Each Value Type is derived from System.ValueType class, so does this mean that Value Type is a class?

For example, if i write:

int x = 5;

it means that i create an instance of System.Int32 class an' write it into variable x??

like image 370
Aleksei Chepovoi Avatar asked Oct 16 '12 19:10

Aleksei Chepovoi


People also ask

Are value types immutable C#?

Short answer: No, value types are not immutable by definition. Both structs and classes can be either mutable or immutable. All four combinations are possible.

Why value types are faster than reference types?

Value types are faster than Reference types, because. Value Types are stored on Stack Memory. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation happens during compilation.

Why value types are stored in stack?

A value type stores its contents in memory allocated in the stack, so we can say value types are allocated in the stack in Swift. ? The misconception is that most people think value types are always stored in the Stack. Value types can be stored inside the stack when they are either temporary or local variables.


2 Answers

The System.ValueType class is really just a "meta" class, and internally is handled differently than normal classes. Structs and primitive types inherit System.ValueType implicitly, but that type doesn't actually exist during runtime, it's just a way for assemblies to mark that a class should be treated like a value type struct and take on pass-by-value semantics.

Contrary to the other answers, value types are not always allocated on the stack. When they are fields in a class, they sit on the heap just like the rest of the class data when that object is instantiated. Local variables can also be hoisted into an implicit class when used inside iterators or closures.

like image 57
Mike Marynowski Avatar answered Sep 28 '22 20:09

Mike Marynowski


See Eric Lippert's article.

In short, a value type is copied by value. Value types are classes just like reference types, and instances of value types are objects. 5 is an object, an instance of System.Int32 (int for short).

like image 21
Thom Smith Avatar answered Sep 28 '22 22:09

Thom Smith