What use is a structure?
/It is exam season here in Hull. Later in the week we have our programming exam. And I’m getting quite a few questions through about C# and stuff. Today I got asked the question “What use is a struct?”. I’ve been spending a lot of time talking about classes and references and how clever they are, and someone wants to know why, if classes are so wonderful, some objects in a program are managed by value. The answer is simple enough. It is because sometimes you really want a value which you can just copy around easily.
Consider the Rectangle type in XNA. We can use this to represent the position and size of something on the screen. And this is a struct, not a class. Take a look at this code:
a = b; a.X = 99;
If a and b are both Rectangle variables the effect would be to set a to the value in b and then move the X position of a to 99. This would not affect the position of b.
If the Rectangle type was a class then we would have two references, a and b, that both refer to the same object in memory, so moving a would affect b as well. If we want to place objects in lots of different positions on the screen, and we don’t want them to be linked in any way, then structures managed by value is the way to do it.
Note that things like Textures are managed by reference. This makes a lot of sense too. An image is a large thing, and it is often very useful to be able to share one image for a whole bunch of things. Think multiple sprites in a space shooter. They will have a Rectangle value to give them a unique position and then a reference to a texture that they all share, to give them an appearance.
The XNA framework is full of objects that are actually structures because they work better this way. For example Color, Point and the Vector objects are all structs so that we can manage them by value. In fact, now that you know how it works, you should be able to look at any XNA type and figure out whether it is a class or a struct, just based on how it is used.