Init-only methods: call-once initialization semantics for methods #9872
Unanswered
Zombach
asked this question in
Language Ideas
Replies: 2 comments 2 replies
-
|
Is this pattern so common that requiring a few lines of code per instance is onerous? The fact that this proposal doesn't seem to actually enforce any guardrails on the invocation and instead it just results in a runtime exception seems to tee it up as a pit of failure. |
Beta Was this translation helpful? Give feedback.
2 replies
-
|
An init-only method is called a constructor. If you want to do async or any real work in a constructor, use a factory method that calls the constructor at the end. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Motivation
C# provides
initaccessors for properties, allowing values to be set onlyduring object initialization. However, there is no equivalent way to express
"call-once during initialization" semantics for methods.
In practice, developers sometimes need:
Today this is typically implemented via private flags and runtime checks,
which is verbose, error-prone, and not discoverable in the type system.
Proposed Feature
Introduce init-only methods, which can be called only during the
object initialization phase and only once per instance.
Example syntax:
Use
now
But if we want to initialize an object through a method, especially an asynchronous one or one that requires multiple parameters, we end up writing something like:
The problems here are:
Interaction with
requiredthe
requiredkeyword, given the analyzability constraints of method calls.worth discussing whether a limited form could be considered in the future.
Beta Was this translation helpful? Give feedback.
All reactions