digitalmars.D.learn - Object initializers
- simendsjo (47/47) Jan 08 2012 C# has Object Initializers:
http://msdn.microsoft.com/en-us/library/bb384062.aspx Java has Double Brace Initializers: http://www.c2.com/cgi/wiki?DoubleBraceInitialization D has with: http://dlang.org/statement.html#WithStatement The nice thing about object initializers is that you can initialize properties not supported by ctor in-place: someFunction(new C { property = value }); or new C { d = new D { /*something*/ } } Are there a good D idom to do something like this? I'm pretty sure though :) This is a little test using mixin (which obviously isn't of any real use) T init(T, string Q, A...)(A params) { auto c = new T(params); with(c) { mixin(Q); } return c; } class C { int _i; property void prop(int i) { _i = i; } string _a; int _b; this(string a, int b) { _a = a; _b = b; } } void main() { auto c = init!(C, q{ prop = 10; })("a", 2); assert(c._i == 10); assert(c._a == "a"); assert(c._b == 2); } Or with a delegate instead: T init(T, A...)(void delegate(T) dg, A params) { auto c = new T(params); dg(c); return c; } auto c = init!(C)((C o) { o.prop = 10; }, "a", 2); Extremely ugly and hard to read :)
Jan 08 2012