Information Technology Reference
In-Depth Information
That introduces some subtle bugs in your application. The compiler does
not help you find these bugs. It's all because of boxing. Start with a sim-
ple structure that lets you modify one of its fields, and put some of those
objects in a collection:
public struct Person
{
public string Name { get ; set ; }
public override string ToString()
{
return Name;
}
}
// Using the Person in a collection:
var attendees = new List < Person >();
Person p = new Person { Name = "Old Name" };
attendees.Add(p);
// Try to change the name:
// Would work if Person was a reference type.
Person p2 = attendees[ 0 ];
p2.Name = "New Name" ;
// Writes "Old Name":
Console .WriteLine(attendees[ 0 ].ToString( ));
Person is a value type. The JIT compiler creates a specific closed generic
type for List<Person> so that Person objects are not boxed, because they
are stored in the attendees collection. Another copy gets made when you
remove the Person object to access the Name property to change. All you
did was change the copy. In fact, a third copy was made to call the
To S t r i n g ( ) f u n c t i o n t h r o u g h t h e a t t e n d e e s [ 0 ] o b j e c t . F o r t h i s a n d m a n y
other reasons, you should create immutable value types (see Item 20).
Ye s , v a l u e t y p e s c a n b e c o n v e r t e d t o S y s t e m . O b j e c t o r a n y i n t e r f a c e r e f e r -
ence. That conversion happens implicitly, complicating the task of finding
them. Those are the rules of the environment and the language. The box-
ing and unboxing operations make copies where you might not expect.
That causes bugs. There is also a performance cost to treating value types
Search WWH ::




Custom Search