Curriculum
In C#, a struct
is a value type that represents a small, lightweight object. It is similar to a class, but it is allocated on the stack instead of the heap, which makes it more efficient in certain situations.
Here is an example of defining a struct
in C#:
struct Point { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } }
In this example, we define a struct
called Point
with two fields, X
and Y
, and a constructor that initializes these fields. We can create instances of this struct like this:
Point p = new Point(3, 4);
We can access the fields of this struct using the dot notation, just like with a class:
int x = p.X; int y = p.Y;
Rules to keep in mind while using structs
:
structs
are value types, which means they are copied by value rather than by reference. This can have performance benefits in some cases, but it also means that changes made to a struct
variable do not affect other variables that hold the same value.structs
can contain fields, properties, methods, operators, and events, just like classes. However, they cannot inherit from other structs
or classes, and they cannot be inherited from.structs
cannot have a parameterless constructor, as they are value types and must have all their fields initialized.structs
are typically used for small, lightweight objects that are frequently created and destroyed, such as points, rectangles, and other geometric shapes. They are also commonly used for defining immutable data types, such as date/time values or currency amounts.structs
when you need a small, simple type with value semantics, and to use classes for more complex types that require reference semantics and more advanced features such as inheritance and polymorphism.Overall, structs
provide a lightweight and efficient way to represent small, simple objects in C#, and they can be a useful tool in certain situations. However, it’s important to understand their limitations and use them appropriately.