Easy differences between a class and a struct

Let us know about what is a class and struct in detail and then summarize the important differences between class and struct in C#

Classes and Structs are two logical structures available to store data in C#.

Classes are reference types that are used for complex behavior and objects, while structs are simple data structures that can be used when you want to store lightweight data with a value type behavior.

What is a Class?

A Class is a logical structure that holds members and behavior together. A Class is a reference type, when you create an instance of a class it refers to a memory location where the object is stored.

Multiple variables can hold references to the same object and modifying one variables can reflect change in all other variables.

Objects are memory allocated in a heap, and are garbage collected when we need to remove the objects from the memory.

class instances are initialized to null by default. they refer to an object location only when we use a new keyword. a class instance can derive from another class via inheritance and extend its behavior.

Since class instances are reference types, if you pass a class instance variable to another method or component, only the reference is passed but not the actual memory block itself.

Any changes that happen in that method over the object using that reference will reflect in the original location as well. to copy an object into another object, you will need to do a shallow copy of the object.

A Class is –

  • Pass by reference structure that points to a memory location
  • Suitable for storing larger structures and types
  • Stored in the heap and Garbage Collected
  • Initialized to NULL by default
using System;

public class Book
{
    // Properties
    public string Name { get; set; }
    public double Price { get; set; }
    public string Isbn { get; set; }

    // Constructor
    public Person(string name, double price, string isbn)
    {
        Name = name;
        Price = price;
        Isbn = isbn;
    }

    // Method to print the person's information
    public void BookInfo()
    {
        Console.WriteLine($"Name: {Name}");
        Console.WriteLine($"Price: {Price}");
        Console.WriteLine($"ISBN: {Isbn}");
    }
}

public class Program
{
    public static void Main()
    {
        // Creating an instance of the Book class
        Book book = new Book("The Alchemist", 350, "112233445566778899");

        // Using the PrintInfo method to print the Book information
        book.PrintInfo();
    }
}

What is a Struct?

A Struct is also a logical structure that can hold members. It is a value type.

If you create an instance of a Struct, the variable contains the value directly and not a reference to some memory location.

Struct variables are memory allocated in a stack or within the memory location where it is used, similar to any other value types. These are automatically de-allocated when they go out of scope.

Struct instances are initialized to their default values based on the types. Numeric types are initialized to 0 and reference types (such as strings) are initialized to null.

Struct types don’t support inheritance, they are simple data structures and can be used only for storing simple data.

When you pass a Struct variable to a method, you are passing the entire value to the method scope and any modification doesn’t reflect in the original location where the method is called.

A Struct is –

  • Pass by value structures and value is passed directly
  • Suitable for smaller structures
  • Stored in a Stack or inline within Memory
  • Initialized to the default values of its property data types
public struct Rectangle
{
    // Properties
    public int Length { get; }
    public int Breadth { get; }

    // Constructor
    public Point(int l, int b)
    {
        Length = l;
        Breadth = b;
    }

    // Method to print the Rectangle's dimensions
    public void PrintDimensions()
    {
        Console.WriteLine($"Length: {Length}, Breadth: {Breadth}");
    }
}

public class Program
{
    public static void Main()
    {
        // Creating an instance of the Rectangle struct
        Rectangle rectangle = new Rectangle(5, 3);

        // Accessing the properties of the rectangle struct
        Console.WriteLine($"Length: {rectangle.Length}");
        Console.WriteLine($"Breadth: {rectangle.Breadth}");

        // Using the PrintDimensions method to print the rectangle's dimensions
        rectangle.PrintDimensions();
    }
}

Summary – Difference between Class and Struct

ClassStruct
BehaviorLogical Structure which is a Reference TypeLogical Structure which is a Value Type
Memory AllocationMemory allocated in a Heap and is Garbage CollectedMemory allocated in a Stack or inline when used within an object, and is removed when out of scope
Initial ValueInitialized to NULL unless the variable is assigned to a new object with new keywordInitialized to the default values of its member data types – 0 for Numeric, NULL for string or reference properties
Parameters and CloningReference is passed when passed as parameter and any change affects the object at calling location.
To clone an object, you need to do a shallow copy of the object.
Value is passed directly when passed as parameter and any change affects the object at calling location.
Assigning to a new variable automatically copies the value to the new variable
Suitable forSuitable for complex members and behaviorSuitable for storing simple data types and can be used a simple data structure

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *