Tech Point Fundamentals

Thursday, January 21, 2021

Structure in C# | Struct in C#

Structure in C# | Struct in C#

Structure-Or-Struct-In-CSharp

Structures are used to represent a record or data structure that can contain both data members and function membersStructures in C# are quite different from traditional C or C++.  Please read my previous constructor and destructor articles. In this article, we will learn about structures in detail.




Structure (Struct)

A structure or struct is a simple user-defined type, a lightweight alternative to a class. A struct is simply a composite data type consisting of any number of other types. The struct keyword is used for creating a structure.

In C#, unlike class, a struct is the value type. In C# reference types are allocated on the heap and garbage-collected, whereas value types are allocated either on the stack or inline in containing types and deallocated when the stack unwinds or when their containing type gets deallocated. Therefore, allocations and deallocations of value types are in general cheaper than allocations and deallocations of reference types.



Structs are particularly useful for small data structures that have value semantics. For example  Complex numbers, points in a coordinate system, or key-value pairs in a dictionary. It is also possible to use structs and operator overloading to implement new primitive types in the C# language. 

In C# all struct types are implicitly inherited from System.ValueType which, in turn, inherits from the System.Object class, so, it is possible to override the methods of the Object class inside a struct by using the keyword override. Remember that this is a special case in C# structs. 




Structure Fundamental Points

    1. In C# structs are value types.
    2. The default modifier is internal for the struct and its members.
    3. A structure can contain only a parameterized constructor or a static constructor.
    4. Like a class, a structure can also contain constants, fields, methods, properties, indexers, operators, events, and nested types.
    5. A struct can also contain static members, but a static member of the struct type is referenced.
    6. This pointer can be used in the structure, but the meaning of this is different for structs ( i.e. this access).
    7. A struct can also be passed by reference to a method using a REF or OUT parameter.
    8. Boxing and Unboxing are used internally to convert between a struct type and an object.
    9. The default value of a struct consists of the value that results from setting all value type fields to their default value and all reference type fields to null.


Structure Fundamental Rules

    1. A struct does not support inheritance, but it can implement interfaces. So a struct cannot inherit from any struct or class.
    2. The accessibility of a struct member cannot be protected or protected internal because inheritance is not supported for structs.
    3. A struct member cannot be specified as abstract, sealed, virtual. But a structure can be partial.
    4. A struct cannot contain any explicit default constructor i.e. parameterless constructor because every struct implicitly has a parameterless instance constructor that always sets the default value to its member fields.
    5. Parameterized constructors are allowed but destructors or finalizers are not allowed in any structure.
    6. A structure can never be abstract because all the structures are implicitly sealed. So abstract and sealed modifiers are not allowed in a struct declaration.
    7. Instance field members declarations for a struct are not permitted to include variable initializers. However static fields of a struct are permitted to include variable initializers.
    8. It is not possible for the value of a struct type to be null because structs are not referenced types.
    9. A struct instance object can be created with or without the new keyword, the same as primitive type variables. If you use the new keyword it calls the default parameterless constructor of the struct which initializes all the members to their default value. But if you create the object without a new keyword, it does not call any constructor, so all the members remain unassigned. Therefore, you must assign values to each member before accessing them, otherwise, it will give a compile-time error.



Related Articles


Example


 

If you see the structure IL Code of the structure, it is sealed implicitly:

Structure-ILCode
Click on the image to zoom



Immutable Structure (readonly struct)

Beginning with C# 7.2, a readonly modifier can be used to declare an immutable structure type. In a readonly structure, all data members also must be read-only. This guarantees that no member of a readonly struct modifies the state of the struct.

public readonly struct ImmutableStructure {  }

In C# 8.0 and later, other instance members except constructors are implicitly readonly. But in a readonly struct, a data member of a mutable reference type still can mutate its own state. For example, you cannot replace a list type instance but you can add a new element into it.

So beginning with C# 8.0, you can also use the readonly modifier to declare an instance member. By doing this an instance member doesn't modify the state of a struct. If you cannot declare the whole structure type as readonly, use the readonly modifier to mark the instance members that do not modify the state of the struct. But you cannot apply the readonly modifier to static members of a structure type.



Reference Type Structure (ref struct)

Beginning with C# 7.2, you can use the ref modifier in the declaration of a structure type. Instances of a ref struct type are allocated on the stack and cannot escape to the managed heap.

A ref struct cannot implement any interface. A ref struct cannot be boxed to System.ValueType or System.Object.

public ref struct MyRefStruct { }

You can also declare a ref struct as readonly, by combining the readonly and ref modifiers in the type declaration. But the readonly modifier must come before the ref modifier.

public readonly ref struct MyImmutaableRefStruct { }



Structure vs Class in C#

    1. All the structs are value types while classes are reference types.
    2. Structs cannot have destructors, but classes can have destructors. 
    3. Structs cannot have an explicit default constructor while a class can have a default constructor.
    4. Structs do not support inheritance while classes support inheritance.
    5. Instance field declarations for a struct are not permitted to include variable initializers while a class can initialize the field members.
    6. In C# user can copy one structure object into another one using the assignment operator (=) but a class cannot be.
    7. A structure cannot have an abstract, virtual, or sealed members while a class can have.
    8. A structure cannot have a sealed method but a class can have sealed methods.
    9. A structure can only override the Object class virtual methods while a class can override any base class virtual method and abstract method.



Advantage of Structure

    1. Since struct is a value type, it is faster than a class object. 
    2. Use struct whenever you want to just store the data.
    3. A structure can be copied into another object by using the assignment operator.
    4. Generally, structs are good for game programming.
    5. It is a lightweight alternative to a class.



Real Examples of Structure

Structs are particularly useful for small data structures that have value semantics. The simple types provided by C# are in fact struct types internally except string.

    1. System.Char
    2. System.Byte, System.SByte
    3. System.Int16(short), System.Int32 (int), System.Int64 (long)
    4. System.UInt16(ushort), System.UInt32(uint), System.UInt64 (ulong)
    5. System.Decimal
    6. System.Single (float)
    7. System.Double
    8. System.Boolean (bool)

Live Demo





Recommended Articles


Abstract Class Vs Interface in C# 8
Partial Interface Methods in C# 8
Interface Member Modifiers in C# 8
Multiple Interface Inheritance in C# 8
Interface Virtual Method in C# 8
Interface Access Modifiers in C# 8




Thanks for visiting this page. Please follow us on Twitter, Facebook, LinkedIn, Telegram, Youtube, and Pinterest for regular updates.


No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.