26.3 Why use a struct?


Even if you have never heard of structs before reading this chapter, the chances are that you have already used them quite a bit. Simple (or primitive) types in C# are implemented as structs internally. [14]

[14] Your sbyte , short , int , long , byte , ushort , uint , ulong , float , double , decimal , char , and bool types are all internally implemented as structs.

You should choose to use a struct rather than a class for performance reasons. If you are writing a class that:

  • represents a small data structure with few data members , [15] and

    [15] Examples of simple data structures better implemented as structs than classes include a complex number (with only two fields “ a real part and an imaginary part), a point of the coordinate system (with only two fields “ an x value, and a y value), or a key/value pair (with only two fields “ a key and a value).

  • does not require the use of inheritance, and

  • it is convenient for it to be a value type instead of a reference type,

you might want to consider implementing it as a struct instead.

26.3.1 Performance implications

Being a value type, a struct is created on the stack rather than on the heap. Operations involving structs generally perform faster for this reason. It is often superfluous to implement a simple and small data structure as a class. One thing which a developer scrutinizing code for optimization should do is search for classes that would be better implemented as structs.

However, because a struct is a value type, an assignment results in the whole struct's value being copied over. If you have a huge struct containing many members, a simple assignment operation may be inefficient since the whole struct is being duplicated . If implemented as a class instead, an assignment is as simple as setting the second reference variable to point to the same object (which is already on the heap anyway).

Consider both sides before deciding if you want a struct or a class.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net