An Introduction to Structs in C#

A struct is a value type that is often used to house a group of related variables, such as the points of a rectangle, together. Structs share many characteristics with classes but they are, at the same time, very different. In this post, we will explore those commonalities and differences and explore some use cases for a struct.

What is the Difference Between a Struct and a Class?

As it turns out, a struct and class have many things in common. They both can have constants, fields, methods, properties, operators, events, constructors, and indexers. A struct can inherit from an interface but not from a class or another struct. Structs are value types while classes are reference types. If you don’t know the difference between a value type and a reference type, read this post. You can set the value of a struct from an external caller just like you would for a class. However, setting the values of a struct inside the struct itself is more difficult. You cannot initialize the properties to a default value and structs do not allow a default constructor because a default constructor is created automatically. If your struct has a non-default constructor, each property in the struct must be set in that constructor. A compile-time error will occur otherwise.

Listing 1.1 – A Simple Struct

public struct SurfaceStruct
{
    public int Width;
    public int Height;
    public int Area;

    public SurfaceStruct(int width, int height)
    {
        Width = width;
        Height = height;
        Area = Width * Height;
    }
}

When to Choose a Struct Over a Class?

Very rarely. There are two rules you should remember when deciding. First, since a struct is a value type, it resides on the stack. That means it should be kept to a very small size. 64 bits should be the upper limit, just like the designers of the .NET Framework have done. Second, ask yourself if any of the properties for the proposed struct make sense without the others. If they do, you should create a class. If not, a struct may be right for you. Also, if you are creating a struct and any of your properties are reference types, you should be using a class.

Conclusion

Structs are a valuable tool in programmer’s toolbelt but their uses are limited. In this post, we have looked at the differences between a struct and a class and when to choose one or the other. I hope it was helpful.

Leave a Reply

Your email address will not be published.