Information Technology Reference
In-Depth Information
// call it:
MyData v = Foo();
TotalSum += v.Value;
If MyData is a value type, the return value gets copied into the storage for
v. However, if MyData is a reference type, you've exported a reference to an
internal variable. You've violated the principle of encapsulation (see Item 26).
Or, consider this variant:
public MyData Foo2()
{
return myData.CreateCopy();
}
// call it:
MyData v = Foo();
TotalSum += v.Value;
Now, v is a copy of the original myData. As a reference type, two objects
are created on the heap. You don't have the problem of exposing internal
data. Instead, you've created an extra object on the heap. If v is a local vari-
able, it quickly becomes garbage and Clone forces you to use runtime type
checking. All in all, it's inefficient.
Ty p e s t h a t a re u s e d to e x p o r t d a t a t h ro u g h p u b l i c m e t h o d s a n d p ro p e r t i e s
should be value types. But that's not to say that every type returned from
a public member should be a value type. There was an assumption in the
earlier code snippet that MyData stores values. Its responsibility is to store
those values.
But, consider this alternative code snippet:
private MyType myType;
public IMyInterface Foo3()
{
return myType as IMyInterface ;
}
// call it:
IMyInterface iMe = Foo3();
iMe.DoWork();
Search WWH ::




Custom Search