Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use default property value in C# constructor initializer

Tags:

c#

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;
like image 204
danrah Avatar asked Jan 22 '26 20:01

danrah


2 Answers

Well, you can simplify it by using null coalescing operator:

  var foo = new Foo();
  foo.Bar = bar ?? foo.Bar;

Or you can change property to check for null values and ignore them :

    private string _bar = "foobar";
    public string Bar
    {
        get { return _bar; }
        set { _bar = value ?? _bar;  }
    }

Then you can use this code to instantiate Foo :

   var foo = new Foo() { Bar = bar };

Note that now if bar is null its value will be ignored in property's setter.

like image 188
Fabjan Avatar answered Jan 25 '26 09:01

Fabjan


Easiest and most readable (IMHO) solution would be:

var foo = new Foo();
if (bar != null)
    foo.Bar = bar;

There is no way to make the validation like you suggested in the initializer (at least not as of C# 6). You could use some constructs with extracting your default to constant like other answers here suggest, but this takes away from readability and does not make using the class easier - you have to know about implementation (default value in the constant) details, which breaks the encapsulation.

If your main concern is about code style, I suggest you get used to ifs, because there is nothing wrong with them and are easy to understand for someone else maintaining your code or yourself in a few months.

If there is something else you need, like validation of the property value, you need to place it in the setter itself (and you should have stated so in the question).

like image 34
slawekwin Avatar answered Jan 25 '26 11:01

slawekwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!