Understanding and Using Structs in C#: Value Types and Their Advantages
Learn about structs in C#, lightweight value types used for representing data. This tutorial explains the key differences between structs and classes (value vs. reference types), demonstrates struct usage, and highlights scenarios where structs offer performance advantages over classes.
Understanding Structs in C#
In C#, structs are value types used to represent lightweight data structures. They're similar to classes but have key differences in how they are stored in memory and how they behave when assigned or passed as arguments.
Value Types vs. Reference Types
Structs are value types, unlike classes, which are reference types. This distinction significantly impacts how they're used:
- Value Types: Data is stored directly in the variable. When you assign a value type variable to another, a copy of the value is created. Changes to one variable don't affect the other.
- Reference Types: The variable stores a reference (memory address) to where the data is stored. Assigning one reference variable to another creates another pointer to the same data. Modifications via one variable will also affect the other.
Example 1: Basic Struct
public struct Rectangle {
public int width;
public int height;
}
This defines a `Rectangle` struct with fields for width and height. You create instances using the `new` keyword.
Example 2: Struct with Constructor and Method
Structs can have constructors and methods. Constructors are used for initialization, and methods provide functionality related to the struct's data.
public struct Rectangle {
public int Width;
public int Height;
public Rectangle(int w, int h) { Width = w; Height = h; }
public int Area() { return Width * Height; }
}
Important Note: Inheritance and Interfaces
Structs in C# do not support inheritance (you can't create a struct that inherits from another struct or class). However, they *can* implement interfaces.