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
};
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.
Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.
Initializers execute before the base class constructor for your type executes, and they are executed in the order in which the variables are declared in your class. Using initializers is the simplest way to avoid uninitialized variables in your types, but it's not perfect.
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
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With