Object Initializer and Dynamically specifying properties
Asked Answered
H

3

7

With an object initializer, is it possible to optionally include setting of property?

For example:

Request request = new Request
{
    Property1 = something1,
    if(something)
        Property2 = someting2,                                      
    Property3 = something3
};
Honeysuckle answered 10/2, 2010 at 2:48 Comment(0)
R
4

Not that I'm aware of. Pretty sure your only option is to do it like this:

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

Or you could do it like this if there's a default/null value you can set it to:

Request request = new Request
{
    Property1 = something1,
    Property2 = something ? someting2 : null,
    Property3 = something3
};   
Rosenkranz answered 10/2, 2010 at 2:52 Comment(0)
H
2

No. Object initialisers are translated into a dumb sequence of set statements.

Obviously, you can do hacks to achieve something similar, like setting the property to what you know the default value to be (e.g. new Request { Property2 = (something ? something2 : null) }), but the setter's still gonna get called -- and of course this will have unintended consequences if the implementer of Request decides to change the default value of the property. So best to avoid this kind of trick and do any conditional initialisation by writing explicit set statements in the old pre-object-initialiser way.

Hammy answered 10/2, 2010 at 2:52 Comment(0)
Y
0

No, since those are static calls they can't be removed or added at runtime based on some condition.

You can change the value conditionally, like so:

Foo foo = new Foo { One = "", Two = (true ? "" : "bar"), Three = "" };
Yvoneyvonne answered 10/2, 2010 at 2:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.