Classes

.NET Structs

Defining Structs

.NET structs are value types with lightweight data.

Introduction to .NET Structs

In .NET, a struct is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of a point. Unlike classes, structs are value types, which means they are stored on the stack and hold their data directly. This makes them more efficient for certain use cases, especially when dealing with small data structures.

Defining a Struct in C#

To define a struct in C#, you use the struct keyword followed by the struct name. A struct can contain fields, methods, properties, and constructors, but it cannot contain a parameterless constructor or a destructor. Here is a basic example of a struct:

Structs vs Classes

Structs and classes are both used to define custom data types in C#. However, there are several key differences between them:

  • Memory Allocation: Structs are value types and are allocated on the stack, whereas classes are reference types and are allocated on the heap.
  • Inheritance: Structs do not support inheritance, meaning they cannot inherit from another struct or class, nor can they be the base of a class. However, they can implement interfaces.
  • Default Constructor: Structs cannot have a default (parameterless) constructor, while classes can.

When to Use Structs

Structs are often used when you need a simple data structure that does not require the overhead of a class. They are ideal for small, immutable data types that will not be modified after creation. Common use cases include:

  • Representing a coordinate or point in 2D or 3D space.
  • Defining a lightweight data structure for performance-critical applications.
  • Encapsulating a small set of related data, such as a color with RGB values.

Limitations of Structs

While structs are useful, they come with certain limitations:

  • Immutability: Structs should be immutable to avoid unexpected behavior, which can limit their flexibility.
  • Boxing and Unboxing: Converting a struct to a reference type (object) or from a reference type back to a struct can lead to performance issues due to boxing and unboxing operations.
Previous
Classes