Joydip Kanjilal
Contributor

How to work with structs in C#

opinion
Mar 09, 20164 mins
Software Development

Take advantage of structs in C# to build small composite data types and avoid the garbage collection overhead

While there are similarities aplenty between a class and a struct, there are some distinct differences too. Most importantly, a struct unlike a class, is a value type. So, while instances of a class are stored in the heap, instances of a struct are stored in the stack.

When an instance of a struct is passed to a method, it is always passed by value. This is in contrast to what happens when we pass an instance of a class to a method — the instance is passed by reference.

Programming structs in C#

Here’s how the syntax for declaring a struct looks like.

<modifiers> struct <name of the struct>

{

//Data members and member functions of the struct

}

The following code snippet shows how a typical struct definition looks like.

struct Rectangle

    {

        public int width;

        public int height;

    }

You can now assign values to the members of the struct you have defined earlier as shown in the code snippet below.

Rectangle rectangle = new Rectangle();

rectangle.width = 10;

rectangle.height = 15;

The above code snippet creates an instance of the Rectangle struct and assigns values to the public members of it. Note that you can have both member data and methods inside a struct. Also, you can specify the members as private, public and internal. It should be noted that unlike classes, you cannot have field initializers for non-static fields in structs. Hence, statements like the following in a struct are not valid.

int width = 10;

int height = 15;

You can initialize static members in your structs anyway. Hence the following is a valid statement inside a struct.

static int area = 0;

Let’s now add a few methods to the struct. Here’s the updated version of the Rectangle struct we created earlier. Note the usage of the parameterized constructor.

struct Rectangle

    {

        int width;

        int height;

        public Rectangle(int width, int height)

        {

            this.width = width;

            this.height = height;

        }

        public int GetArea()

        {

            return this.width * this.height;

        }

    }

Note that even if a struct doesn’t allow you to define an explicit parameterless constructor inside it, you can always have parameter constructors inside a struct. Also, similar to a class, you can have overloaded constructors in a struct as well. Here’s how you can set values using the constructor of the Rectangle struct and then get the area by invoking the GetArea() method. It should be noted that similar to a class, you can have static and nonstatic methods inside a struct.

static void Main(string[] args)

        {

            Rectangle rectangle = new Rectangle(10, 15);

            int area = rectangle.GetArea();

            Console.WriteLine("The area is: " + area.ToString());

            Console.Read();

        }

Like a class, a struct provides support for properties and indexers. One major difference between a struct and a class is that unlike a class, a struct doesn’t support inheritance — you cannot have a struct that extends another class or a struct. However, similar to a class a struct can implement an interface. Here’s a code example that illustrates this.

 interface IRectangle

    {

        int GetArea();

    }

  struct Rectangle : IRectangle

    {

        int width;

        int height;

        public Rectangle(int width, int height)

        {

            this.width = width;

            this.height = height;

        }

        public int GetArea()

        {

            return this.width * this.height;

        }

    }

Choosing between a class and a struct

Now we come to an interesting point of debate. When should we use a struct over a class and vice-versa?

As we discussed earlier in this article, an instance of a struct is created in the stack while an instance of a class is created in the managed heap. Allocation and deallocation of value types are cheaper than reference types. A struct is a good choice when you need to create a composite data type that would hold a few data members. Ideally, the size of the data members of a struct should be less than 16 bytes. You can opt for a struct when you would want to build a small composite data structure that has value semantics and contains only a few data members. In using struct in such cases, you can avoid the overhead associated with garbage collection.

You should follow the recommended best practices when working with structs. You should avoid using a struct that is of a larger size than what is recommended in this article. Also, note that passing instances of structs to methods are more costly in terms of performance than passing instances of classes. It is advisable to use structs when you are working with small data structures.You can learn more on this topic from this MSDN article.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author