Reflection

Structs

The C# struct is a lightweight alternative to a class. It can do almost the same as a class, but it's less "expensive" to use a struct rather than a class. The reason for this is a bit technical, but to sum up, new instances of a class is placed on the heap, where newly instantiated structs are placed on the stack. Furthermore, you are not dealing with references to structs, like with classes, but instead you are working directly with the struct instance. This also means that when you pass a struct to a function, it is by value, instead of as a reference. There is more about this in the chapter about function parameters.

So, you should use structs when you wish to represent more simple data structures, and especially if you know that you will be instantiating lots of them. There are lots of examples in the .NET framework, where Microsoft has used structs instead of classes, for instance the Point, Rectangle and Color struct.

First I would like to show you an example of using a struct, and then we will discuss some of the limitations of using them instead of classes:

The observant reader will notice that this is the exact same example code as used in the introduction to classes, besides the change from a class to a struct. This goes to show how similar the two concepts are. But how do they differ, besides the technical details mention in the beginning of this chapter?

First of all, fields can't have initializers, meaning that you can't declare a member like this:

private string color = "Blue";

If you declare a constructor, all fields must be assigned to before leaving the constructor. A struct does come with a default constructor, but as soon as you choose to define your own, you agree to initialize all fields in it. That also means that you can't declare your own paramaterless constructor - all struct constructors has to take at least one parameter. In our example above, we did in fact assign a value to the color field. If we hadn't done that, the compiler would complain.

A struct can not inherit from other classes or structs, and classes can't inherit from structs. A struct does inherit from the Object class, but that's it for inheritance and structs. They do support interfaces though, meaning that your structs can implement custom interfaces.