How is a struct used in C#?

In C#, a struct is a type of value data structure used to store a set of related data fields. Unlike classes, structs are value types, not reference types, which means they store values directly in memory rather than references.

Structures are typically used to represent lightweight data objects, such as coordinates, dates, times, etc. They are suitable for storing a small amount of data and are more efficient because they allocate memory on the stack rather than the heap.

Here is how to use a struct in C#:

  1. Declare a struct: Use the struct keyword to declare a structure. For example:
  2. A structure called Point is defined with two public integer variables, X and Y.
  3. Creating an instance of a struct: Structs can be instantiated by using the new keyword. For example:
  4. Create a new point with coordinates (10, 20).
  5. Struct properties and methods: Structs can have properties and methods, similar to classes. Properties and methods can be defined within a struct to manipulate the struct’s data. For example:
  6. A structure called Point is defined, with two public integer variables X and Y. It also includes a public method called Move that takes two integer parameters, deltaX and deltaY, and adds them to X and Y respectively.
  7. Passing structures: Structures are value types, when a structure is passed as a parameter to a method, a copy of the value is made. This means that modifications to the structure within the method will not affect the original value of the structure. For example:
  8. Change the value of the point object’s X coordinate to 100 without affecting the original struct value.

In conclusion, structs in C# are used to store lightweight data objects, and because they are value types, they offer high performance. They can have properties and methods, can allocate memory directly on the stack, and copy values when passed.

bannerAds