Wednesday, February 27, 2008

[.NET] Quick and Dirty guide to choosing between Struct and Class

Hey there, welcome to the .NET Butchering quick and dirty guide to choosing between Struct and Class. You probably already know that Structs are value types (everything on the stack) while classes are reference types (reference on the stack, actual allocation on the heap), and allocation on the stack is generally cheaper in terms of performance far small stuff and so on; if you didn't know you do now. If you need inheritance there's not much to think about since Structs do not support it, but if you don't just refer to the following bulletlist; if you can identify as FALSE one of the items on the list, then a bullet hits you and your doubt is killed: you go for Class. If you go through the bulletlist without being hit Struct is instead your way to go:
  • You are trying to represent a single value - let's say you're looking fo a way to wrap a built-in type like a string in order to make your code more readable (do not if you will to get the .NET Butchering Certification):

    Struct myBoringReadableType
    string value;
    //all your properties and crap

    Another good example could be the classic representation of a Point as a Struct (which I am not going to write here).

  • The size of your instance is gonna be less than 16 Bytes - If you plan to stuff your soon-to-born type with more than 16 Bytes (i.e. [4 int] - [2 double] - [2 int, 1 double] - [1 decimal] - [16 Byte] ... ) you're done thinking: go for a class. Moving such a fat-ass on the stack is definitely not worth it.

  • Your instance will be IMMUTABLE (or something like that) - If your type is a mutable one by concept, and you plan to change it all the time, you should go for a class.

  • You plan NOT to cast your instance to a reference type - In other words you don't plan boxing your potential struct. Simpler example of this is casting to Object.

That's it. Hope you find it Quick and dirty enough.

1 comment:

Mike said...

Long time since you post that but I think it's valid to point out that this post is full of awesomeness. I couldn't find a better explanation anywhere else.

Thanks for this.