I am wondering how to use late-initialized class fields in C# with nullable reference types. Imagine the following class:
public class PdfCreator {
private PdfDoc doc;
public void Create(FileInfo outputFile) {
doc = new PdfWriter(outputFile);
Start();
}
public void Create(MemoryStream stream) {
doc = new PdfWriter(stream);
Start();
}
private void Start() {
Method1();
// ...
MethodN();
}
private void Method1() {
// Work with doc
}
// ...
private void MethodN() {
// Work with doc
}
}
The above code is very simplified. My real class uses many more fields like doc
and also has some constructors with some arguments.
Using the above code, I get a compiler warning on the constructor, that doc
is not initialized, which is correct. I could solve this by setting the type of doc
to PdfDoc?
, but then I have to use ?.
or !.
everywhere it is used, which is nasty.
I could also pass doc
as a parameter to each method, but remember that I have some fields like this and this violates the clean code principle in my eyes.
I am looking for a way to tell the compiler, that I will initialize doc
before using it (actually I do it, there is no possibility for the caller to get a null reference exception!). I think Kotlin has the lateinit
modifier exactly for this purpose.
How would you solve this problem in "clean" C# code?