Information Technology Reference
In-Depth Information
or class keyword when you create the type, but it's much more work to
update all the clients using your type if you change it later.
It's not as simple as preferring one over the other. The right choice depends
on how you expect to use the new type. Value types are not polymorphic.
They are better suited to storing the data that your application manipu-
lates. Reference types can be polymorphic and should be used to define
the behavior of your application. Consider the expected responsibilities
of your new type, and from those responsibilities, decide which type to
create. Structs store data. Classes define behavior.
The distinction between value types and reference types was added to
.NET and C# because of common problems that occurred in C++ and
Java. In C++, all parameters and return values were passed by value. Pass-
ing by value is very efficient, but it suffers from one problem: partial copy-
ing (sometimes called slicing the object). If you use a derived object where
a base object is expected, only the base portion of the object gets copied.
Yo u h a v e e f f e c t i v e l y l o s t a l l k n o w l e d g e t h a t a d e r i v e d o b j e c t w a s e v e r t h e r e .
Even calls to virtual functions are sent to the base class version.
The Java language responded by more or less removing value types from
the language. All user-defined types are reference types. In the Java lan-
guage, all parameters and return values are passed by reference. This strat-
egy has the advantage of being consistent, but it's a drain on performance.
Let's face it, some types are not polymorphic—they were not intended to
be. Java programmers pay a heap allocation and an eventual garbage col-
lection for every variable. They also pay an extra time cost to dereference
every variable. All variables are references. In C#, you declare whether a
new type should be a value type or a reference type using the struct or
class keywords. Value types should be small, lightweight types. Reference
types form your class hierarchy. This section examines different uses for a
type so that you understand all the distinctions between value types and
reference types.
To s t a r t , t h i s t y p e i s u s e d a s t h e r e t u r n v a l u e f r o m a m e t h o d :
private MyData myData;
public MyData Foo()
{
return myData;
}
 
Search WWH ::




Custom Search