In C# 9, one can define a property with the same name in a record both in its primary constructor and in its body:
record Cat(int PawCount)
{
public int PawCount { get; init; }
}
This code compiles without errors.
When initializing an instance of such a record, the value provided to the constructor is completely ignored:
Console.WriteLine(new Cat(4));
Console.WriteLine(new Cat(4) { PawCount = 1 });
prints
Cat { PawCount = 0 }
Cat { PawCount = 1 }
Is this behavior correct or is it a bug? If it’s correct, what are the cases in which it is useful?
I expected the compiler to either reject this code with an error like ‘The type Cat
already contains a definition for PawCount
’ or consider the property in the constructor and in the body the same, performing its initialization from the constructor.
The latter variant could be useful to provide the property with a custom getter and/or initializer without having to rewrite all the properties of the positional record in its body.
The actual behavior makes no sense to me.