C# Struct versus Class
2008 07 25 – 7:21 amI’ve been working on an in-house inventory management system for the last few weeks. During the course of the project, I’ve been faced with a few design decisions that I thought would be nice to share here.
As if the title weren’t a dead giveaway, I’ve had to decide on using classes or structs for holding data I intend to output or input. So, basically, I needed a mechanism for hold values that I set once and then output to the screen or input to the database.
The main difference between a struct and a class is the type of object they are. A struct is a value type where as a class is a reference type. This means that structs share the behavior of other value types such as int32, DateTime, etc. In effect, a struct will behave like any other variable you declare. Once you are no longer in the context where the variable was declared, it will cease to exist and when passing the value to a method, you are sending a copy of the struct rather than a reference.
A class must be instantiated with the ‘new’ keyword. Like I mentioned before, classes are reference types. This means that when an object is created it exists until there are no more references to that instance of the class–at which point it will be garbage collected. When passing an instance of a class to a method, you are passing a reference to that instance. This means that the method will manipulate that instance rather than a copy.
There are performance considerations for using a struct or a class. Generally, the concensus is that a struct should be small, how small? 16 bytes or less. Structs are thrown on the stack where as classes are put on the heap. A struct that is not too large, will generally perform better than a class. Using a List<> will also avoid the performance hit of boxing and unboxing a struct into and out of a collection.
So when do you use a struct over a class? As a rule, if my object exists for the sole purpose of holding a value, then I tend to choose a struct. If my object has to perform work, I will use a class. However, when in doubt, use a class.
A professional software developer on the .Net and LAMP platforms.
I enjoy walks on the beach, SQL Server, video games, and college sports.