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#:
- Memory allocation: struct variables are allocated on the stack, whereas class variables are allocated on the heap.
- 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.
- 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.
- Inheritance: class supports inheritance, while struct doesn't.
- 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#:
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#:
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.
- Advantages of C#
- C# vs. Java: What Are Its Main Differences
- Advantages of C# over Python
- First C# Program | Hello World
- Difference between Console.Write and Console.WriteLine in C#
- How do I create a MessageBox in C#?
- C# Comments
- How to reverse a string in C#
- Palindrome in C# with Examples
- Fibonacci Series Program in C# with Examples
- C# Program to Print Number Triangle
- Get Integer Input from User in C# Console Application
- C# StringBuilder | Learn To Use C# StringBuilder Class
- C# HashMap (Dictionary)
- Ternary Operator (? :) in C# with Examples
- How To Sort Datatable in C#
- Async And Await In C#
- IEnumerable in C# | Examples
- ref Vs out in C#
- How to remove item from list in C#?
- How to Add Items to a C# List
- C# StreamWriter Examples
- StreamReader in C# |Examples
- C# Map Example
- Static Method In C# | Examples
- How to convert an Enum to a String in C#
- How to convert a string to an enum in C#
- How to filter a list in C#?