Difference Between Struct And Class In C#

In C#, both struct and class are used to define custom types, but there are some differences between them in terms of behavior, usage, and performance. Following are some details about struct and class in C#.

Differences between struct and class in C#:

  1. Memory allocation: struct variables are allocated on the stack, whereas class variables are allocated on the heap.
  2. Copying behavior: When a struct variable is assigned to another variable, the entire data is copied. When a class variable is assigned to another variable, only the reference to the data is copied, not the entire data.
  3. Default initialization: When a struct variable is created, its fields are automatically initialized to their default values (e.g., 0 for integers). When a class variable is created, its fields are initially null.
  4. Inheritance: class supports inheritance, while struct doesn't.
  5. Interfaces: struct can implement interfaces, while class can implement interfaces and abstract classes.

When to use struct or classes?

Following are some examples of situations where you might choose to use a struct or a class in C#:

Struct

When you need a small, lightweight data type:

Since struct variables are allocated on the stack and copied by value, they are typically faster and more memory-efficient than class variables. So if you need a data type that is small and doesn't require a lot of functionality, a struct might be a good choice. For example, a Point structure that stores X and Y coordinates.

When you want to avoid heap allocations:

In some cases, you might want to avoid creating objects on the heap to reduce pressure on the garbage collector. For example, if you are working with a high-performance application that requires a lot of memory allocation and deallocation, using structs instead of classes can help to reduce memory fragmentation and improve performance.

Class

When you need a complex, flexible data type:

A class is a good choice when you need a data type that is more complex and requires more functionality than a struct. For example, a Person class that includes properties like Name, Age, Address, and methods like GetFullName() and SaveToDatabase().

When you need to create a hierarchy of types:

Class supports inheritance, which means you can create a hierarchy of types that inherit behavior and functionality from their base classes. For example, you could create a Vehicle base class and then derive specific types like Car, Truck, and Motorcycle.

When you need reference semantics:

Since class variables are passed by reference, you can use them to create shared objects that can be accessed and modified by multiple parts of your application. This can be useful in scenarios where you need to maintain state or share data between components. For example, a UserSession class that tracks the user's login status and preferences across multiple pages of a web application.

Struct in C#

A struct is a value type in C#, meaning that when a variable of a struct type is assigned to another variable, the entire data is copied. struct variables are stored on the stack, which is faster and has less overhead than the heap. In C#, a struct is defined using the struct keyword, and it can contain fields, methods, properties, and events.

Follwoing is an example of a struct in C#:

public struct Point { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public override string ToString() { return $"({X},{Y})"; } }

In the above example, Point is a struct that has two integer fields X and Y, a constructor that initializes these fields, and an override of the ToString method to return a string representation of the point.

Class in C#

A class is a reference type in C#, meaning that when a variable of a class type is assigned to another variable, only the reference to the data is copied, not the entire data. class variables are stored on the heap, which has more overhead and is slower than the stack. In C#, a class is defined using the class keyword, and it can contain fields, methods, properties, events, and other members.

Following is an example of a class in C#:

public class Person { public string Name; public int Age; public Person(string name, int age) { Name = name; Age = age; } public void SayHello() { Console.WriteLine($"Hello, my name is {Name} and I'm {Age} years old."); } }

In the above example, Person is a class that has a string field Name, an integer field Age, a constructor that initializes these fields, and a method SayHello that writes a greeting to the console.