Nullable new aka nullable Constructor #7755
Replies: 3 comments 6 replies
-
Given that a constructor cannot return Nevermind, that is what the proposal is asking for. The lead was a tad buried, but that's my fault for not reading the whole thing before commenting. IMO, allowing for constructors to override the value that is returned, whether that be to return |
Beta Was this translation helpful? Give feedback.
-
just some background on what drove this idea. I was adding constructors to a bunch of classes |
Beta Was this translation helpful? Give feedback.
-
Supporting object initializers for factory methods is this proposal: #6602 |
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.
-
Summary
Proposes a syntax that allows
new()
to return a null, allowing the use of property initializers where previously a Factory function would have been required.Problem
Sometimes when you are constructing a instance of a class you may wish to return null. Since
new()
cannot return null a factory function is often used. However a factory function does not allow access to the languages property initializer features, making code that does this require more boilerplate (specifically parameters passed to the factory function).Idea/Proposal:
create new syntax for new
new?()
and for constructorspublic Ctor?()
that indicate the new operation may not return an instance of the object. Property initilizer syntax would then be chainablecalling
Advantages
?
innew?()
ornew Gadget?()
makes it explicit that a null may be returnedstatic NullableObject? Create()
pattern. as a pattern many differnt ways of naming the same method existCreate
,Make,
CreateGadget,
MakeGadget,
ConstructGadget,Construct
, etc. A quick search of github and it appears this pattern is extremely common.Disadvantages
new
has always returned a constructed object, no longer doing so is a big shift from the way things were.Possible implementation
Since property initializers are already just syntatic sugar for setting properties after new() returns and
init;
is just syntatic sugar that is converted to a setter that the complier only lets you call during initialization.so
could be converted to
Issues
Issues with Rewriting to valid IL
Create
method is probably difficult if left unbounded, so this proposal probably needs to be tweaked to address the issue.return null
orreturn new()
Final thoughts
I was surprised there was not a discussion on this already, which hopefully is not because I am bad a searching, or that my idea is silly.
I think that new language features should be simple, be consistent with existing syntax, and reduce the need for patterns in code. I believe this idea meets that criteria.
Addendum
the driving example provided above under this proposal would appear as below
Beta Was this translation helpful? Give feedback.
All reactions