Consider the following class:
class Foo
{
public string Bar { get; set; } = "foobar";
}
And this piece of code:
var foo = new Foo {
Bar = bar == null
? null
: bar
};
Obviously, the value of Bar would be null after the execution of this code (suppose that bar = null).
I want the constructor initializer to use default property value in given cases (e.g. when bar is null). I want to know if there is an easier way to do this instead of using:
if (bar == null) {
foo = new Foo();
} else {
foo = new Foo { Bar = bar };
}
Or
foo = new Foo();
if (bar != null)
foo.Bar = bar;
if (bar != null) { ... }var foo = new Foo(); if (bar != null) foo.Bar = bar;.