Reputation: 3955
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??
Upvotes: 7
Views: 1511
Reputation: 14086
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).
Upvotes: 1
Reputation: 21024
Now, there's a lot to talk about that. Seriously, there's like hundred of pages about this topic on the net, and most of it burns my cerebral matter at an alarming rate.
What I actually remembered is, int and Int32 is the same thing, and both act like a struct, not a class. "int" being a shortcut to Int32. (If you put your mouse over a int, the tooltip reads "struct System.Int32". Which means:
public class BoxedInt
{
public int x;
public BoxedInt(int i) { x = i; }
}
public Test()
{
BoxedInt bi = new BoxedInt(10);
Boxed(bi);
Console.WriteLine(bi.x); // Returns 11, as any reference type would.
int vi = 10;
Valued(vi);
Console.WriteLine(vi); // Returns 10, because it acts like a struct. (Which it is)
}
public void Boxed(BoxedInt i)
{
i.x++;
}
public void Valued(int i)
{
i++;
}
Upvotes: 0
Reputation: 3439
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.
Upvotes: 6
Reputation: 13
Value Types are not classes. These are builtin types in languages and are handled by .NET CTS (Common Type System). CTS is a component inside CLR which is responsible for handling the value types such as bool, int, double, float etc. When you create an object of value type then it is created on stack. When you pass it to a function or return from a function then a new object is created for it in ram. But in case of reference types, only reference of object is passed and new object is not created inm memory. There are some userdefined value types which are not in language specification and are defined by users. Such value types are inherited from System.ValueType. Example of such valuetype is Complex number. We can make our own userdefined type of complex numbers using System.ValueType.
Upvotes: -2