C# Struct vs Class |Top 15+ Differences Between C# Struct and Class

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

C# struct vs class
C# struct vs class

Class

A Class is a user-defined blueprint, prototype, or template for creating objects. It is basically used to contain fields, properties, and methods of different data types, which can be accessed and used by creating an instance of that class. We can create a new class by using the class keyword followed by the class name.

Struct

A structure is a user-defined value type data type. It allows you to create a single variable to hold related data of different data types.
We can create a structure by using the struct keyword followed by the structure name.

C# Struct vs Class

The following is the list of differences between struct and class in C#.

  • In C#, Class is a reference type, whereas Struct is a value type.
  • A class object is allocated on the heap memory, whereas Struct type variables are allocated on the stack memory.
  • All struct types implicitly inherit from the class System.ValueType whereas every class is implicitly a subclass of the 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 types.
  • 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 a reference type, Boxing and unboxing operations are used to convert between a struct type and an object in C#.
  • In C#, Destructors are not allowed in structures, but they are allowed in classes.
  • Parameterless constructors are not allowed in the structure. However, parameterized and static constructors are allowed. A class, on the other hand, can have any kind of constructor.
  • 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 a struct, which means that you cannot declare a member of the structure like the below image:
field initializers in struct in C#
Field initializers in the struct

Parameterless constructors and field initializers in the 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 are now allowed to initialize an instance field or property during declaration time with C# 10.

Example:

using System;
namespace StructInCSharp
{
    // Example: field Iinitializers in a struct  in C#10
    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:

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)
        }
    }
}

When To 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.

You can consider using a structure in the following scenario:

  • If an instance of a type is small and generally short-lived or often embedded in other objects, then struct should be used instead of class.
  • We can use a 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, a 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 a single instance and change 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 the structure is the way to go. If any of the members are of the reference type, use Class.
  • We can consider structs because they do 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 for the case mentioned above, you should declare your type as the class.

Reference MSDN: Class and struct differences

Conclusion:

This article demonstrates the basic difference between struct and class in C#. Here, we learned how to create a struct and why to choose struct over class in C#.
Structs in C# are basically the 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 memory.

Recommended Articles

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments