Consider the following classes in C# 11:
class BaseClass
{
public required string BaseProperty { get; init; }
}
class ChildClass : BaseClass
{
public required string ChildProperty { get; init; }
}
The standard way to initialize the derived class is:
var a = new ChildClass
{
BaseProperty = "abc",
ChildProperty = "def"
};
This works fine but becomes tedious if the base class has a lot of properties or there are many derived classes. Is there any way to use a common, centralized initializer for the base class such that only the additional properties need to be initialized for derived classes? Something like (invented syntax follows):
void Main()
{
var a = new ChildClass : BaseInitializer()
{
ChildProperty = "def"
};
}
BaseClass BaseInitializer()
{
return new BaseClass
{
BaseProperty = "abc"
};
}
Without this functionality it seems that the required
and init
keywords are only useful for basic scenarios not involving inheritance.
My question is a bit similar to Can I set SetsRequiredMembers or another attribute for only one member in C# 11?, except that question is asking how to apply a broad attribute to only one property, while I am wondering how to use two different initializers on the same instance.