- Author

- Name
- Nelson Silva
- Social
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:
- Assignment Type: While a
structis a value type, a class is a reference type. This fundamental difference dictates behavior in various operations, especially in assignment and parameter passing. - Inheritance:
structsdo not support inheritance, except inheritance from interfaces. - Constructors: A
structcannot have a parameterless constructor. However, it can have parameterized constructors. - Destructors:
structscannot have destructors. Destructors are used in classes to perform any necessary cleanup before an object is collected by the garbage collector. - Access modifiers: The
protectedmodifier does not make sense in astruct, 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.