'Do records generate overrides for inherited positional properties?
Consider the following record definitions:
public record BaseRecord(string Text)
{
public string Text { get; init; } = Normalize(Text);
// ...
}
public record DerivedRecord(string Text) : BaseRecord(Text)
{
// ...
}
BaseRecord will have the normalized value for Text. But does DerivedRecord reuse the Test property from BaseRecord, or does it generate a new one that ignores the normalized base value?
Further: What if BaseRecord did not have Text as a positional parameter, but only as a regular property?
Solution 1:[1]
Shortly after finishing writing the question, I came up with this test code.
This experiment answered my question directly, but an answer that provided more details, insight, or generally explained in more detail the way code is generated for derived records would be valuable.
public class Program
{
public static void Main()
{
var x = new DerivedRecord("text", "derived other");
var (text, other) = x;
Console.WriteLine(text);
Console.WriteLine(other);
}
}
public record BaseRecord(string Text)
{
public string Text { get; init; } = Text.ToUpper();
public string Other { get; init; } = "base other";
// ...
}
public record DerivedRecord(string Text, string Other) : BaseRecord(Text)
{
// ...
}
Running it on https://dotnetfiddle.net/ printed "TEXT" rather than "text", which suggests to me that the base property is being used in DerivedRecord. Additionally, the second line said "base other" rather than "derived other", which suggests not only that DerivedType even re-used the base Other property, but maybe also that it completely ignores the value given to the constructor as a result.
Solution 2:[2]
The purpose of inheritance for record types is to add additional properties to existing record types.
Consider this more simplified example:
public record BaseRecord(string Text);
public record DerivedRecord(string Text, string Other) : BaseRecord(Text);
The user expects now from DerivedRecord a record type with 2 properties: Text and Other.
The compiler sees that BaseRecord already has the property Text and only adds Other as another property.
If the compiler would not do this, there would be 2 properties named Text where the derived property would hide the base property (known as shadowing) which is definitely not a behavior you want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TheRubberDuck |
| Solution 2 | Jannik |
