Structure in C#

Structure

Structures are also user defined data type like Classes. They are used when we need a data type according to our requirements. So with the help of this, we can create a data type of which a single variable can hold many data types by having different variables with different data types.

Properties of Structures in C#

Structures can have constructors, fields, constants, methods, operators and nested types as data types. Structures can’t inherit themselves from another structure, but they can implement an interface. Structures can have all access specifiers, but they cannot have protected access specifier.

Syntax:

Struct syntax in C#
Struct syntax in C#

 

Example of Structure in C#:

The struct keyword is used to define a structure. And by default the scope of structure variables is private so to make them public, we have to write public key work separately with each variable.

Difference between class and structure:

Although both of them are the user defined data types, they have some difference among each other.

  • Structures are the value type, and class is the reference type.
  • Inheritance is not done using structures.
  • Structures have no constructor by default.

Structure Example:

Class using a structure:

Advantages of Structures:

Structures have functions, attribute, objects, and events.

There is no destructor and default constructor in C# structure, but you can create a defined constructor.

Inheritance is not possible using structure but in the case of interfaces.

As inheritance is not allowed to use structures so, there is no base and super-structure.

Structure can’t do inheritance, but has the ability to implement an interface.

There is no virtual, abstract function in the structure.

Structure object is created using the new keyword in C#.