Partial constructor extensions #8546
-
Currently we can do a lot with code generators where we define a full type using source generators. This means that a little metadata can create a fully realised structure. If we use this to create something like this: [GeneratedCode("MyGenerator", "1.0.0")]
public partial class MyClass
{
public int One { get; }
public string Two { get; }
public double Three { get; }
public MyClass(double param)
{
One = 1;
Two = "2";
Three = param;
}
} This is intended to be extended with bespoke functionality by a programmer like so: public partial class MyClass
{
public DateTime CurrentTime { get; }
private MyClass()
{
CurrentTime = DateTime.Now;
}
} The generator can then detect this and modify the original code to call the constructor public MyClass(double param)
: this()
{
One = 1;
Two = "2"; Once this happens we know that all the variables will be initialised but the compiler still generates warnings for CS8618 as the human authored constructor doesn't initialise the generated properties. ProposalAdd an extra keyword to a method declaration that gives it the power to initialise getter only parameters but limits the method
This means our generated code turns to this: [GeneratedCode("MyGenerator", "1.0.1")]
public partial class MyClass
{
public int One { get; }
public string Two { get; }
public double Three { get; }
public MyClass(double param)
{
One = 1;
Two = "2";
Three = param;
}
private partial KEYWORD void Init();
} and the human authored class moves it's initialisation logic to public partial class MyClass
{
public DateTime CurrentTime { get; }
private partial KEYWORD void Init()
{
CurrentTime = DateTime.Now;
}
} Now the compiler can look at all constructors and check if they are calling any constructor extension that sets a property and know that all types will be initialised. Personal candidates for the keyword that denotes this are Additional use cases
Similar proposals#318 different as this is not applicable to properties |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
I think that init methods are the most likely path forward for this. Those would be methods callable from constructors or other |
Beta Was this translation helpful? Give feedback.
I think that init methods are the most likely path forward for this. Those would be methods callable from constructors or other
init
methods that have the ability to setreadonly
members. If that were available then you could use apartial init
member that the source generator could fill out.