Search code examples
c#-9.0record-classes

How to use `Data members` in C#-9


I was trying the new syntax for C# 9 but I failed to use the Data members.

Documents say the syntax is:

public data class Person { string FirstName; string LastName; }

However, I faced the following compile errors:

CS0116: A namespace cannot directly contain members such as fields or methods
IDE1007: The name 'data' does not exist in the current context.

I have tried other syntaxes and they all worked. So, I am sure that I am using C#-9

Update: This question is suggested as a possible answer.

But, it is not my answer and I believe the accepted answer in that link is wrong. Record types and data members are two different things. Data members are a new way to define immutable types, while the record types are Value Objects.
Documents suggest that in the data member classes you just need to define the properties like private fields, so the Person is equal to:

public data class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

Solution

  • data classes are now called record. They are the same, immutable objects which behave like value types (exhibiting structural or in other words value based equality).

    Regarding your code in OP,

    public data class Person { string FirstName; string LastName; }
    

    could be rewritten as

    public record Person(string FirstName, string LastName);
    

    The above syntax uses Primary Constructor . If you would like to skip the primary constructor, you could also declare records as

    public record Person
    {
        public string FirstName { get; init; }
        public string LastName { get; init; }
    }
    

    In either cases, the Properties, FirstName and LastName could be assigned only during initialization (either via Constructor or object initializers) and not after that.