C# What is difference between class & Record type

T.Zacks 3,996 Reputation points
2021-11-29T17:47:04.327+00:00

We know that Record types which have been introduced in C# 9.0. see the code and tell me what is difference between these two set of code ?

i found one article said about Record as follow

1) Immutable means it cannot change. By default, Record types are immutable.
2) Record Type - it is a compact and easy way to write reference types (immutable) that automatically behave like value type

why people saying record behave like value type....what does it mean?

public class Member  
{  
    public int ID { get; init; }  
    public string FirstName { get; init; }  
    public string LastName { get; init; }  
    public string Address { get; init; }  
}

and

public record Member  
{  
    public int ID { get; init; }  
    public string FirstName { get; init; }  
    public string LastName { get; init; }  
    public string Address { get; init; }  
}

the only difference is Record keyword used in 2nd code. other than this what is difference ?

**1) please discuss with some sample code which i can run and understand the difference & usage.

2) when to use record type....please discuss a scenario.**

thanks

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-11-29T18:38:49.877+00:00

    You need to read the docs

    Immutable means it cannot change. By default, Record types are immutable.

    Yes this is true and that you can create immutable instances of a List and other collections, see the following blog entry. In this case a class would have a public getter and private setter.

    For sample usage of records see the following.

    Records: The goal is that you can more easily create immutable records while with classes more work is required.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.