how to create a record inheriting the attributes of another record without explicitly rewriting them in C#

Viewed 25

Is it possible to factor the record parameters, to make the code easier to modify?

for exemple if I have :

public record A(int Param1, int Param2, int Param3, int Something);
public record B(int Param1, int Param2, int Param3, string OtherThing);
public record C(int Param1, int Param2, int Param3);

I want something like :

public record Base(int Param1, int Param2, int Param3);
public record A(int Something) : Base;
public record B(string OtherThing) : Base;
public record C() : Base;

So if someday I want to modify Param1, I can do it only once instead of doing it in 3 records.

1 Answers

The type signature of a record is the constructor definition of the type. As long as you want your constructor to have all the "attributes" as you call them, you need to type them all in.

What this means:

public record Specific1(int Attr3) : Global;

This won't compile because there is no constructor in Global with no parameters. Contrast this with the following instead:

public record Specific1(int Attr3) : Global(0, 0);

Which does compile, though might not do what you want. Again, the parameters you write in your record declaration are the parameters present in your constructor.

Related