created on 2018-04-08

#computer-science #dot-net

Struct vs. Class in .NET

Lately, I've made a very important mistake while using structs in our persistency system(save/load game). So I wanted to write this post, which may help others, especially Unity developers. Since they mostly use C# in their programs.

So what is the difference between a struct and a class? Everybody should and probably do know by heart that, struct is a value type and class is a reference type in C#. The things is most people do not know what this means and what are the effects. I am going to give some examples to explain these effects.

  1. struct MyStruct
  2. {
  3. public int a;
  4. }
  5. MyStruct myStruct;
  6. myStruct.a = 1; // Don't do this and you are going to get a compile error

If you use the new keyword, then the fields will be assigned to their default values. (e.g. 0 for int)

  1. public static void UpdateA(this MyStruct ms)
  2. {
  3. ms.a += 1; // The passed ms object's field 'a' is still 1, remember pass by value
  4. }
  1. public static MyStruct RecursiveA(MyStruct ms)
  2. {
  3. ms.a += 1;
  4. if (ms.a < 10)
  5. {
  6. RecursiveA(ms);
  7. }
  8. return ms;
  9. }
  10.  
  11. ms = RecursiveA(ms);

The function above will still terminate when ms.a is 10 but the value of the actual ms.a will be 1. You can solve this problem by using a class of course or you can assign ms inside the function like this.

  1. public static MyStruct RecursiveA(MyStruct ms)
  2. {
  3. ms.a += 1;
  4. if (ms.a < 10)
  5. {
  6. ms = RecursiveA(ms);
  7. }
  8. return ms;
  9. }
  1. public static MyStruct RecursiveA(ref MyStruct ms)
  2. {
  3. ms.a += 1;
  4. if (ms.a < 10)
  5. {
  6. RecursiveA(ref ms);
  7. }
  8. return ms;
  9. }
  10. // When this terminates the value of ms.a will be 10
  11. RecursiveA(ref ms);

Conclusion

I think it is clear that a mutable struct is not a good idea. They are good for storing read-only data. Whenever you need mutable data, you should use a class instead of a struct.

If you think that this blog post is wrong or missing, please send me a message.