In C# a structure is a value type data type. It helps you to make a single variable hold related data of various data types.
A structure is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events and nested types.
A structure in C# is simply a composite data type consisting of a number elements of other types. A C# structure is a value type and the instances or objects of a structure are created in stack. The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types.
The struct keyword is used for creating a structure. Structures are used to represent a record.
Example of Structure is:
public struct Discounts
{
public int Cloths { get; set; }
public int HomeDecor { get; set; }
public int Grocery { get; set; }
}
A struct can be initialized with or without the new keyword same as primitive variable or an object. You can then assign values to the members of the structure as shown below.
Discounts saleDiscounts = new Discounts();
saleDiscounts.Cloths = 20;
saleDiscounts.HomeDecor = 10;
saleDiscounts.Grocery = 5;
Features of C# Structures:
1. Structure can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types.
2. Structure cannot include default constructor or destructor.
3. Structure can implement interfaces.
4. A structure cannot inherit another structure or class.
5. Structure members cannot be specified as abstract, virtual, or protected.
6. Structures must be initialized with new keyword in order to use it is properties, methods or events.
Class vs Structure
1. Class is reference type where as struct is value type.
2. Struct cannot declare a default constructor or destructor. However, it can have parametrized constructors.
3. Struct can be instasntiated without the new keyword. However, you won t be able to use any of its methods, events or properties if you do so.
4. Struct cannot be used as a base or cannot derive another struct or class.
5. structures do not support inheritance.