Skip to main content
Published on

struct in C#

Share:

Introduction

The C# language is rich in types, offering programmers a wide variety of tools to solve problems. Among these tools are structures (structs), which are especially useful for representing lightweight objects that have value semantics.

What is a structure (struct)?

In C#, a struct is a value type used to encapsulate small amounts of related data. Due to its value-type nature, it directly occupies space in memory, avoiding heap allocation, which makes it faster in certain circumstances compared to classes.

Structures vs Classes

Differences between structs and classes:

  1. Assignment Type: While a struct is a value type, a class is a reference type. This fundamental difference dictates behaviour in various operations, especially in assignment and parameter passing.
  2. Inheritance: structs do not support inheritance, except inheritance from interfaces.
  3. Constructors: A struct cannot have a parameterless constructor. However, it can have parameterised constructors.
  4. Destructors: structs cannot have destructors. Destructors are used in classes to perform any necessary cleanup before an object is collected by the garbage collector.
  5. Access modifiers: The protected modifier does not make sense in a struct, since they do not support inheritance.

When to use a struct?

structs are ideal in situations where:

  • The instance is small and has value semantics.
  • It is desirable to avoid heap allocations.
  • The object represents a single logical value, such as a number or data point.

Practical Example

Here is an example of a struct in action:

using System;

namespace Base {
  class Struct {
    public void Run() {
      var structure = new Structure();
      structure.Number = 200;

      // The number must be >= 0 and <= 100.
    }
  }

  struct Structure : INumber {
    private int number;

    public int Number {
      set {
        if (value >= 0 && value <= 100) {
          number = value;
          PrintNumber();
        }
        else
          Console.WriteLine("The number must be >= 0 and <= 100.");
      }
    }

    public void PrintNumber() {
      Console.WriteLine($"Number: {number}");
    }
  }

  interface INumber {
    void PrintNumber();
  }
}

Conclusion

The choice between using a struct or a class in C# depends on the specific needs of your project. We hope that with this article you have gained a clear understanding of structures and when they can be useful.

Happy coding!