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; }
}
dataclasses are now calledrecord. 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,
could be rewritten as
The above syntax uses Primary Constructor . If you would like to skip the primary constructor, you could also declare records as
In either cases, the Properties, FirstName and LastName could be assigned only during initialization (either via Constructor or object initializers) and not after that.