Game Development Reference
In-Depth Information
int _value;
public Int(int value)
{
_value ¼ value;
}
public void SetValue(int value)
{
_value ¼ value;
}
public override string ToString()
{
return _value.ToString();
}
}
Int i ¼ new Int(100);
Int j ¼ i; // reference type so reference copied into i
Console.WriteLine(i); // 100
Console.WriteLine(j); // 100
i.SetValue(30);
Console.WriteLine(i); // 30
Console.WriteLine(j); // 30 < - the shocking difference
Here when i changed so did j . This is because j did not have its own copy of the
data; it just had the same reference to the data that i did. When the underlying
data changes, it doesn't matter if that data is accessed with i or j , the same result
will always be returned.
To use the library example again, you check the library index system and it re-
turns two shelf locations for the topic you want. The first position, i , doesn't
have a topic at all; it just has a small note, and when you check position j you
find a similar note. Both of these notes points to a third location. If you follow
either note, you will find the topic you were searching for. There is only one
topic, but two references point to it.
Boxing is the process of taking a value type and converting it to a reference type.
Unboxing is the process of converting the new reference type back to the original
value type. In the first version of C#, lists of objects, even if they were all value
types, had to be converted to reference types when they were added to the list. This
all changed with the introduction of generics. Here's some example code using
generic functionality; compare this with the earlier example using an ArrayList .
 
Search WWH ::




Custom Search