Pseudo Constructors #8084
Replies: 3 comments 2 replies
-
I'd honestly just prefer async constructors over factory-like hacks. |
Beta Was this translation helpful? Give feedback.
-
For a long time, I thought about it too, then I changed my mind. Even if asynchronous constructors were technically implementable, they would still be a messy solution. First of all, the typical "Async" suffix is missing, which explicitly indicates the nature of the operation, so you would end up writing: var x = new Foo(); Without it being clear at all that public async Foo() : this/base(...)? The proposed solution avoids all these ambiguities, making the asynchronous operation completely explicit ( |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
The issue of asynchronous constructors has already been discussed, albeit without a solution, in various topics (#419, dotnet/roslyn#6788).
Here, an alternative and more general approach is proposed to achieve a satisfactory result.
Consider an object that requires asynchronous initialization; asynchronous constructors, as extensively discussed, are extremely problematic. Therefore, the solution currently available involves separating the operations:
This syntax is cumbersome as it requires the caller to construct an object in two steps and can be improved with a static method:
This is a standard syntax that we could call the "Factory Pattern." It works, but:
await Foo.CreateAsync(){Property1=1}
this
One possible way out is as follows:
Let's define any static method inheriting from a constructor as a pseudo-constructor. Here are two examples, one related to asynchronous constructors and the other in a completely different context:
this
, even if omitted.A pseudo-constructor follows the nullability rules of a constructor. See C#8 with nullable compiler only checks code in constructors before producing CS8618 warning roslyn#32358.
A pseudo-constructor
that returnsallows initializers:this
or an awaitable ofthis
marc.
Beta Was this translation helpful? Give feedback.
All reactions