Difference Between Struct And Class In C#

In this post, we will explore the variance between struct and class in C#. Prior to delving into their distinctions, it is crucial to understand the concept of struct and class in C#. Both classes and structures are utilized in C# for constructing custom data types, yet they possess significant disparities. In contrast to structures, classes have the capability to inherit from other classes. To put it another way, a structure is incapable of inheriting from a class.

The distinction between a reference type and a value type lies in the fact that classes are reference types. This implies that each instance of a class generates a reference to the object, and modifications made to the object will be visible wherever the reference is accessed.

Conversely, a structure represents an integer data type, meaning that when a variable of structure type is instantiated, the specific value of the variable is stored in memory. However, any changes made to these variables are not reflected in other locations.

What is a Class?

A class serves as a custom-designed plan or model utilized in constructing objects. It merges attributes and functions (methods that define operations) into a cohesive entity.

Example:

Filename: Class.cs

Example

using System;
// Define a Writer class
public class Writer {

    // Declare public data members for the writer's information
    public string authorName;        // Name of the author
    public string primaryLanguage;   // Primary programming language
    public int publishedArticles;    // Total published articles
    public int authoredImprovements; // Total authored improvements

    // Method to set and display author details
    public void AuthorDetails(string authorName, string primaryLanguage,
                              int publishedArticles, int authoredImprovements)
    {
        // Set the class data members with provided values
        this.authorName = authorName;
        this.primaryLanguage = primaryLanguage;
        this.publishedArticles = publishedArticles;
        this.authoredImprovements = authoredImprovements;

        // Display author's details using Console.WriteLine
        Console.WriteLine("Author's Name: " + authorName
                        + "\nPrimary Language: " + primaryLanguage
                        + "\nTotal Published Articles: " + publishedArticles
                        + "\nTotal Authored Improvements: " + authoredImprovements);
    }

    // Main method where the program starts execution
    public static void Main(String[] args)
    {
        // Create an instance of the Writer class
        Writer writerObj = new Writer();

        // Call the AuthorDetails method to set and display author details
        writerObj.AuthorDetails("John Doe", "C#", 80, 50);
    }
}

Output:

Output

Author's Name: John Doe
Primary Language: C#
Total Published Articles: 80
Total Authored Improvements: 50

What is Structure?

Structure represents a value type that stores multiple variables of different data types within a unified entity. It resembles a class in that they are both custom data types capable of storing diverse data types. In C#, predefined data types are available for use, but there are instances where users may want to create their own data types, commonly referred to as User-Defined Data Types. Despite being categorized as a value type, structures can be customized by users to suit their specific requirements, thus referred to as user-defined information types.

Syntax:

It has the following syntax:

Example

// Define a C# struct with the following components:
// - Access Modifier (e.g., public, private, internal)
// - Struct Name (the name of the structure)

struct StructureName
{
    // Fields (variables to store data)
    // Parameterized Constructor (a special method to initialize the structure)
    // Constants (immutable values that don't change during runtime)
    // Properties (getters and setters for accessing and modifying data)
    // Indexers (special properties to access elements in the structure)
    // Events (mechanisms for handling and notifying events)
    // Methods (functions that perform actions or calculations)
}

Example:

Filename: Struct.cs

Example

using System;
namespace MyUniqueApplication {

    // Define a structure named PersonDetails
    public struct PersonDetails
    {
        // Declare fields with different data types
        public string FullName;
        public int Age;
        public int BodyWeight;

    }

    class MyProgram {
        
        // Main Method
        static void Main(string[] args)
        {

            // Declare person1 of type PersonDetails
            PersonDetails person1;

            // Assign values to person1's fields
            person1.FullName = "Alice Johnson";
            person1.Age = 25;
            person1.BodyWeight = 65;

            // Display the stored information
            Console.WriteLine("Information about person1: " +
                            "Name: " + person1.FullName +
                            ", Age: " + person1.Age +
                            ", Body Weight: " + person1.BodyWeight);

        }
    }
}

Output:

Output

Information about person1: Name: Alice Johnson, Age: 25, Body Weight: 65

Main Difference between Struct and Class:

There are key distinctions between struct and class in C#. Some primary variances between struct and class are outlined below:

The default constructor is invoked every time an object of a class is instantiated. Conversely, a structure does not have an inherent default constructor.

Initialization: When you instantiate a class object, its attributes are initialized to default values (null for reference types and 0 for value types). Upon creating an instance of a variable type, all its elements are auto-assigned default values. In the case of a structure type variable, users have the option to provide initial values for individual components of the structure.

The magnitude of performance: Structures are generally more compact than classes as they do not encompass reference parameters or additional overhead. This implies that structures might be quicker than classes when it comes to passing as arguments or making copies.

In C#, the main variations between subclasses and structures consist of inheritance, reference type versus value type, default constructor, initialization, and size/performance. Structures are designed for smaller, uncomplicated entities that require swift passing around, while classes are employed for more complex and substantial objects. Nonetheless, both classes and structures come with their own set of pros and cons, with the choice between them being dictated by the specific demands of the project.

Head-to-head comparison between struct and class in c#

There are multiple direct comparisons between struct and class in C#. Some key distinctions between struct and class are outlined below:

Class Structure
Classes are of thereference type Structs arevalue types.
All of the reference types are assigned heap memory. Any of the value types are allotted stack memory.
Allocation of large reference types is less expensive than allocating large value types. Allocation and de-allocation are less expensive in the value type compared to the reference type.
The class has numerous aspects. Struct has limited capabilities.
Classes are commonly utilized in large programs. Structs are used in small programs.
Classes can include constructors and destructors. Structures have not parameter less or destructors, although they may have parameterized or static constructors.
Classes created instances with the new keyword. With or without the new keyword, Struct can generate an instance.
A class can be descended from a different group. It is not permitted for a Struct to inherit from a different struct or class.
A class's data component can be encrypted. A struct's data member cannot be protected.
A class function member can be private or abstract. The struct's function members can't be virtual or abstract.
Two variables of the same class can have the same object's reference. It is and actions performed on one variable can affect another. Every variable in struct has its own copy of data (with the exception of the in-ref and out-parameter variables), and any action performed on one variable has no effect on another.

Input Required

This code uses input(). Please provide values below: