15 - Structs in C#

15.1 Purpose of Struct in C#

Struct is an encapsulated entity. It is a value data type. All the members of struct have to be initiated. It is a simple user defined data type that can be used as an alternative to class. The struct keyword is used for creating a structure.

Structures have behaviors and attributes. They can directly contain the values of the object or instance from the stack. They support access modifiers, constructors, indexers, methods, operators, fields and properties.

15.2 Implement the Struct in C#

The struct can be defined using the struct statement. They add one or more members used in the program. The general structure for defining a struct is as shown below:

struct structure_name{//data members}

Consider a Student structure to be defined. The code sample for the structure is as shown below:

In the above code, the student class creates two objects as st1 and st2 respectively. The objects are used for accessing the members defined in the student structure. The result is displayed using the standard output function.

The structures can be inherited from an interface in an application. The struct do not provide inheritance in C#. It is not possible for a user to inherit from a struct. The struct cannot be derived from a class.

In the above code, the interface calculate consists of two methods as increment and displayresults respectively. The methods defined in an interface can be either private or public. They cannot be used as protected. The employee struct is declared in the application. It inherits the interface. All the methods declared in the interface are used inside the structure.

In Main() method, the values for the different parameters are passed through the Employee constructor.

15.3 Use a Struct

C# struct is a light weighted as compared to the class. They are useful when simple data structures are to be implemented in an application. The struct is created on a stack. The new keyword is not used for creating it.