[Proposal] Object initializers for factory methods
See original GitHub issueProblem
This is another one of the issues when a change to logic significantly changes code structure. Let’s say I had the following:
var x = new X {
A = a,
B = b,
C = { D = { d1, d2 } }
};
Now I decided all X
should be created through an XFactory
instead.
So I get:
var x = factory.CreateX();
x.A = a;
x.B = b;
x.C.D.Add(d1);
x.C.D.Add(d2);
One small logical change causes a total restructure of not-really-related code.
Potential solution
Provide a way to use object initializer with any existing object. Example:
var x = factory.CreateX() with {
A = a,
B = b,
C = { D = { d1, d2 } }
};
Keyword with
here is provided to remove any syntax ambiguities.
Pros
- More consistent syntax everywhere. Shorter syntax for setting a few properties when you need that.
Cons
- New kind of expression-with-side-effects when used on an existing object.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:3
- Comments:9 (3 by maintainers)
Top Results From Across the Web
[Proposal] Factory Initializers - Discussion - Swift Forums
The "factory" pattern is common in many languages, including Objective-C. Essentially, instead of initializing a type directly, a method is ...
Read more >Is it possible to use a c# object initializer with a factory ...
No. Alternatively you could accept a lambda as an argument, which also gives you full control in which part of the "creation" process...
Read more >rfc:object-initializer
factory methods where normally a significant amount of argument has default values or simple Data Transfer Objects could benefit. Note!
Read more >Designing object initialization
Ensure proper initialization of your objects at all times ... When I write about designing with class variables and class methods, I'll describe...
Read more >Exploring the Factory Method Design Pattern
It provides a common interface for creating objects, but the actual class of the object is determined by the subclass implementation. Here's a ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
It’s desirable to allow the same initializers on factories as constructor calls. We need to think this through in conjunction with
with
expressions, and with object initializers for immutable objects.Issue moved to dotnet/csharplang #803 via ZenHub