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]
You should choose to use a struct rather than a class for performance reasons. If you are writing a class that:
you might want to consider implementing it as a struct instead. 26.3.1 Performance implicationsBeing 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. |