Structs in C#
A struct in C# is very simillar to a class but think of it as a lightweight version of a class.
Structs are value types and are stored on the stack rather than the heap so they use less resources.
Lots of built in types are actually structs so when considering whether your object should be a struct or a class then think about how these will be used and compare them with objects which Microsoft have made as structs rather than classes. Note though a tendency to have structs for objects which hold and manipulate values rather than representing rich and functional objects.
Some examples of intrinsic types which are structs are as follows:
- Int16
- Int32
- Int64
- Byte
- float
- double
- DateTime
You can confirm this by right clicking on one of these in Visual studio and clicking to definition when for lets say an Int32 you will see this:
So lets have a look at what a simple struct could look like. We will create one to represent a point on a Graph consisting of an x and y co-ordinate. We will alos create a little console app to use for testing our code.
Ok so hopefully that was simple enough.
Note that we could have written this with fewer lines of code as follows but then we don't have the benefits of using properties just the same as when we are dealing with classes.
Taking the code above let's try adding a Constructor as follows:
If you do this and try and compile then you will get an error saying that Structs cannot contain explicit parameterless constructors.
The reason for this is that structs already have an implicit default constructor built in. If we want to create a constructor then we have to put some code and parameters in it. If we try and get away with just this:
then we again get a compilation error but this time stating that Field 'QuickTest.GraphPoint.Y' must be fully assigned before control is returned to the caller.
so we need to finish it off and :
So we can therefore deduce that you must either not have a constructor(other than the implicit built in one) or if you do have a constructor then this must have parameters and all fields whether private or public must be initialised in the constructor.
Other differences in structs and classes is that structs cannot inherit from other classes but they can implement interfaces.
There are in fact many many more differences between structs and clases. Rather than list them myself I shall point you in the direction of a very good listing and explanation of these: