In C#, the main difference between class and record type is that a record is designed to store data and properties, whereas classes define responsibility which means it contains login, operation, and behavior.
This means that once you create an instance of a class, you can change its properties. in the Record type, you cannot change its properties.
In other words, Both classes and records are used to define data structures, but they have some differences in terms of their intended usage and behavior.
- Classes are reference types that store data on the heap and it is mutable.
- Records are reference types that store data on the heap, however, records are immutable.
Comparison between Classes and Records Types
Here is a list of differences between Record and Class types in C#
Types | Memory Allocation | Performance | Mutability |
Classes | It is stored on the heap. | Slightly slower | Mutable |
Records | It is stored on the heap. | Slightly slower | Immutable |
Let’s understand with an example:
Class in C#
This example defines a class “Vehicle” with two properties “Vehiclename” and “color” and a method “productdetail”.
public static class Program
{
public class Vehicle
{
public string VehicleName { get; set; }
public string Vcolor { get; set; }
public void productdetail()
{
Console.WriteLine("vehicle Name : " + VehicleName + " Color : "
+ Vcolor);
}
}
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle();
vehicle.VehicleName = "Hero Honda";
vehicle.Vcolor = "Gray";
vehicle.productdetail();
vehicle.VehicleName = "Honda";
vehicle.Vcolor = "Black";
vehicle.productdetail();
Console.ReadLine();
}
}
Output:
vehicle Name : Hero Honda Color : Gray
vehicle Name : Honda Color : Black
Record in C#
This example defines a record called Vehicles with properties “VehicleName and “color” Both are defined with a get and init accessor, which means that it can be read and written to only during initialization.
public record Vehicles
{
public string VehicleName { get; init; }
public string Vcolor { get; init; }
}
static void Main(string[] args)
{
Vehicles vehicles = new Vehicles { VehicleName = "Hero Honda", Vcolor = "Black" };
Console.WriteLine($"Vehicle description - {vehicles.VehicleName} { vehicles.Vcolor }");
Console.ReadLine();
}
Output:
Vehicle description - Hero Honda Black
When to Use Record Vs Classes
Record
- When we need to encapsulate data without complicated behavior like your purpose is to contain public data or a Data transfer object
- The record can be a suitable choice when you want to store search parameters.
Classes
- When we need to encapsulate data with complex behaviors and will be the large instance.
- The class is the better choice when the structure changes after the creation of the instance.
Recommended Articles:
Create CRUD operation using Angular and ASP.NET Core Web API
WPF | Windows| Console Application | How to Call REST API in C#
Remove Duplicates from an Array in C# without using a built-in function