Object initializer and dynamically setting properties

With an object initializer, is it possible to enable property setting?

For example:

Request request = new Request { Property1 = something1, if(something) Property2 = someting2, Property3 = something3 }; 
+6
c # object-initializers
source share
3 answers

Not that I knew. It's pretty accurate that your only option is to do it like this:

 Request request = new Request { Property1 = something1, Property3 = something3 }; if(something) request.Property2 = someting2; 

Or you can do it like this if there is a default / null value that you can set for it:

 Request request = new Request { Property1 = something1, Property2 = something ? someting2 : null, Property3 = something3 }; 
+4
source share

Not. Object initializers are translated into a dead end job sequence.

Obviously, you can do hacks to achieve something similar, for example, to set the property according to your default value (for example, new Request { Property2 = (something ? something2 : null) } ), but the setter will still be called - and, of course, this will have unintended consequences if the Request developer decides to change the default value for the property. It’s best to avoid such a trick and perform conditional initialization by writing explicit tasks in the old pre-initializer object.

+2
source share

No, since these are static calls, they cannot be deleted or added at run time based on some condition.

You can change the value conditionally, for example:

 Foo foo = new Foo { One = "", Two = (true ? "" : "bar"), Three = "" }; 
0
source share

All Articles