What is a value type?
While reference types have a layer of indirection
between the variable and the real data, value types don't. Variables of a value
type directly contain the data. Assignment of a value type involves the
actual data being copied.
Take a simple struct, for example,
public struct IntHolder { public int
i;
}
Wherever there is a variable of type IntHolder, the
value of that variable contains all the data - in this case, the single integer
value. An assignment copies the value, as demonstrated here:
IntHolder first = new IntHolder(); first.i=5;
IntHolder second = first; first.i=6; Console.WriteLine
(second.i);
EXAMPLE
using System; using System.Text;
public class Example2 { struct IntHolder
{ public int i; }
public static void Main (string[] args) {
IntHolder first = new IntHolder(); first.i=5;
IntHolder second = first; first.i=6; Console.WriteLine
(second.i); }
}
Output: 5
|
|
Here, second.i has the value 5, because that's
the value first.i has when the assignment second=first occurs - the
values in second are independent of the values in first apart from when the
assignment takes place. Simple types (such as float, int, char), enum types and
struct types are all value types.
Note, many types (such as string appear in some ways to
be value types, but in fact are reference types. These are known as immutable
types. This means that once an instance has been constructed, it can't be
changed. This allows a reference type to act similarly to a value type in
some ways - in particular, if you hold a reference to an immutable object, you
can feel comfortable in returning it from a method or passing it to another
method, safe in the knowledge that it won't be changed behind your back. This is
why, for instance, the string.Replace doesn't change the string it is called
on, but returns a new instance with the new string data in - if the original
string were changed, any other variables holding a reference to the string
would see the change, which is very rarely what is desired. Constrast this
with a mutable (changeable) type such as ArrayList - if a method returns the
ArrayList reference stored in an instance variable, the calling code could
then add items to the list without the instance having any say about it, which
is usually a problem. Having said that immutable reference types act like
value types, they are not value types, and shouldn't be thought of as actually
being value types.
|