How to work with structs in C#

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

Structs in C#

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.

Copyright © 2016 IDG Communications, Inc.