Structures are composite types and can contain different types of elements. That means, structures can contain integer elements, strings, floating point elements, and even other structure types etc.,.
Unlike in C language, C# structures can encapsulates both data elements and the functions which are operating on the data.
Structures are value types.
Defining a structure in C#
C# provides struct
keyword to define a structure. Before you define a structure you need to decide what elements, needs to be part of the structure. Below is the simple example to define a structure.
struct Vehicle { int wheels; int color; string model; };
Accessing elements from the structure
C# provides member access operator (.) to access structure members. But, here is the tricky thing you need understand. Members of the structures can be static or non-static. We must use an instance of the structure
to access it’s non-static members.
<instance of the structure>.<structure member>
C# allows to access the static members of the structure
directly, without creating an instance or object of the structure.
<structure name>.<structure member>
You must also specify the proper access level to the elements of the structure.
Otherwise, C# compiler will through the Error.
For example, an attempt to access wheels
element from the above structure,
without specifying it’s protection level, will show the below Error:
Error 1 'Structures.Program.Vehicle.wheels' is inaccessible due to its protection level
Assigning values to the structure elements
In C#, we can create a constructor in structures to assign the default values to the elements of the structures. C# doesn’t allow to create default constructors (without any parameters). If you attempt to create a constructor in a structure
without any parameters, C# compiler throws the below Error:
Error 1 Structs cannot contain explicit parameterless constructors
As mentioned above, we can assign the values to the structure
members using instance of the structure
(for non-static members) or by directly using the name of the structure
(for static members).
Structures are value types
Unlike classes, structures in C# are value types. That means, when we declare a structure
, the memory of the structure by default allocated in the stack memory; NOT on the heap memory. Another thing is, when we pass structures through function arguments; the structure data will be copied to the arguments; resulting duplicate of data and these are independent copies of the data.
Working example
Let’s put all together what we learned so far about structures and here is the working example;
We will discuss more topics in my upcoming Articles.
(Raju)