6.0 Structs

A struct can implement interfaces and it does that exactly as classes do. You cannot declare a class using the keyword struct. In C#, classes and structs are semantically different. A struct is a value type, while a class is a reference type.

Reference: Microsoft Docs

Structs can be useful when wanting to represent lightweight objects that won't take up much memory. This could help your program be more efficient in some cases.

Structs are very similar to classes. To create a struct we use the keyword struct. Just like classes, structs can have fields, properties, constructors and methods. There are several differences between classes and structs.

  1. A struct is a value type where a class is a reference type.

  2. All the differences that are applicable to value types and reference types are also applicable to classes and structs.

  3. Value types hold their value in memory where they are declared, but reference types hold a reference to an object in memory.

  4. Value types are destroyed immediately after the scope, or variable, is lost. With reference types, only the reference variable is destroyed after the scope is lost. The object is later destroyed by garbage collecting.

  5. When you copy a struct into another struct, a new copy of that struct gets created and modifications on one struct will not affect the values contained by the other struct.

  6. When you copy a class into another class, we only get a copy of the reference variable. Both the reference variables point to the same object on the heap. So, operations on one variable will affect the values contained by the other reference variable.

  7. Structs can't have destructors while classes can have destructors.

Implementation

    public struct CoOrds
    {
        public int x, y;

        public CoOrds(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    }

Optional Reading

Garbage Collection

Next: Enums

Last updated