Proposal: Factory initializer syntax #8331
-
Sometimes we use a factory to return a descendant instance of a certain type, but when you have a bunch of required properties, the parameter list of the factory function would become insanely long, which just negates the benefit of C#'s initializer syntax.
The idea would be like, put a 'new' keyword after the return type of the factory function, which indicates that you will have to return with a new constructed object of the returned type.
So that we can treat the factory function as if it’s a real constructor and can use initializer syntax after it. By using 'TReturn new' instead of 'new TReturn', it won’t conflict with the existing ‘hide inherited function’ syntax. The idea would be that you would have to do ‘new return …’ instead of 'return new ...' in the factory (similar to the syntax of ‘yield return’), as long as you put a ‘new’ keyword after the return type in the definition. The factory function would have to allow you to do ‘return new Item()’ even if you didn’t specify the required fields in the return statement. In that case, the responsibility of setting up the required properties would fall to the caller code of the factory. Perhaps you can still do 'new return Item(){ ... }' initializer in the new return line, and the caller's initializer should add up to it. And naturally, you would also be able to use attributes like [SetsRequiredMembers]:
So that the caller wouldn’t have to set the required fields, but would still have the option to use initializer syntax. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Beta Was this translation helpful? Give feedback.
See Factories / Factory methods sections in #3707 https://github.com/dotnet/csharplang/blob/cf67a0f8ca0ab3b8da79a2f9ea8cb23f253b4e5a/meetings/2020/LDM-2020-04-20.md https://github.com/dotnet/csharplang/blob/cf67a0f8ca0ab3b8da79a2f9ea8cb23f253b4e5a/meetings/2020/LDM-2020-05-04.md