C# Struct vs Class |Top 15 Most Astounding Differences Between C# Struct and Class

C# struct vs class
C# struct vs class

C# Struct vs Class – In C#, Struct and Class are user-defined data types that can contain a variety of data types. The main difference between these two is that class is the reference type, whereas Struct is a value type.

C# Struct vs Class-The Most Important Differences

    • In C#, Class is the reference type, whereas Struct is a value type.
    • The object of Class is allocated on the heap memory, while Struct type variables are allocated on the stack memory.
    • All struct types implicitly inherit from the class System.ValueType where as every class is implicitly a subclass of System.Object class.
    • When the scope is lost, value types are immediately destroyed, whereas reference type objects are only destroyed by the  garbage collector . As a result, value type allocations and deallocations are generally less expensive than reference type.
    • A class is passed by reference to a method; whereas, a structure is passed as a value rather than a reference to a method (except ref and out parameter variables).
    • Since struct is not reference types, Boxing and unboxing operations are used to convert between a struct type and object in C#.
    • In C#, Destructors are not allowed in structures, although they are allowed in classes.
    • Structs are not allowed to contain parameter less constructors, however parameterized constructors and static constructors are allowed. Classes, on the other hand, can have constructors.
    • Structs can be instantiated with or without the new keyword, whereas classes require the new keyword to be instantiated.
    • A class can inherit from another class, but a struct cannot inherit from another struct or class. However, a structure type can implement interfaces.
    • The structure cannot be a base class and is implicitly sealed, while the class can be a base class.
    • By default, members of a class are private, whereas members of a structure are public.
    • The data member of a class can be declared as protected, while the data member of a struct cannot.
    • A struct type variable directly contains the struct data, whereas a class type variable contains a reference to the data.
    • Instance fields cannot have initializers in struct, which means that you cannot declare a member of the structure like below image:
field initializers in struct in C#
Field initializers in struct

Parameterless constructors and field initializers in struct in C# 10.0

Note: Starting with C # 10.0, you can declare a (default) parameterless constructor and field Initializers in a struct type.
You can now initialize an instance field or property during declaration time with C# 10.0, as shown in the following example:

using System;
namespace StructInCSharp
    // Example: field Iinitializers in a struct  in C#10.0
    public readonly struct Employee
        public double Salary { get; init; }

        // Initialize an instance field or property at its declaration
        public string Name { get; init; } = "Shekh Ali";
        public Employee(double salary)
            Salary = salary;
        public override string ToString() => $" Salary= $ {Salary} Name=({Name})";

    public static void Main(string[] args)
        Employee employee = new Employee(5000);
        Console.WriteLine(employee);  // output: Salary= $ 5000 Name=(Shekh Ali)

C# Struct Example

A structure can be created by using the struct keyword.
In C#, a structure-type variable can’t be null so you must initialize a declared variable before it can be used.
The following is an example of how to create a structure in C#.

Example-Instantiation of a structure type in C#

You can also instantiate a structure type without using the new operator if all of its instance fields are accessible. In that situation, all instance fields must be initialized before the instance is used for the first time. The example below demonstrates how to do so:

using System;
namespace StructInCSharp
    public static class StructWithoutNewOperator
        public struct Coordinates
            public double x;
            public double y;

        public static void Main()
            //Example- Struct without new operator
            Coordinates  c;
            c.x = 3;
            c.y = 5;
            Console.WriteLine($" Coordinates : (x = {c.x}, y = {c.y})");

            // Output:  Coordinates : (x = 3, y = 5)

Why Choose Struct Over Class in C#?

There’s a lot of debate over whether we should use class or structure, and the best answers are listed below.

Consider using a structure in the following scenario:

    • If the instances of the type are small and generally short-lived, or if they are frequently embedded in other objects, consider using a structure rather than a class.
    • We can use struct to logically group a number of different value types into a single unit.
    • Consider struct instead of class if the type logically represents a single value, such as primitive types like int, double, and so on.
    • If the type will not be boxed frequently, struct is the best option.
    • Use struct to store the size of a geometric shape, possibly containing a width and height property of type Double each. (example: A point in a 2d or 3d coordinate system)
    • With structures, you have to worry far less about memory leaks or multiple threads to access the single instance, and changing the value of a variable.
    • Another scenario where structs make sense is when the type is immutable. (After a struct has been created, it should not be changed)
    • If all member fields are of value type, then structure is the way to go. If any of the members are of the reference type, use Class.
    • We can consider structs because they does not need to be destroyed by the Garbage Collector since they are immediately deleted from the stack memory once they are no longer in scope.

Except as mentioned above, you should declare your types as classes in all other cases.

Reference MSDN: Class and struct differences


This article demonstrates the basics difference between struct and class in C#. In this article, we learned how to create a struct and why to choose struct over class in C#.
In C#, Structs are lite versions of classes and are extremely similar to them. Both class and structure are user-defined data types. Structures are of the value type and therefore stored on the stack, while classes are of the reference type and are stored on the heap.

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. C# List Class |Top 12 Amazing Generic List Methods
    3. Exception Handling in C#| Use of try, catch and finally block
    4. C# Enum 
    5. C# extension methods with examples
    6. Properties In C# with examples
    7. IEnumerable Interface in C# with examples
    8. Constructors in C# with Examples
    9. C# Dictionary

Leave a Comment