Home > Blockchain >  Initialize a value when not null (or leave the default if new value is null)
Initialize a value when not null (or leave the default if new value is null)

Time:02-04

If I have an object, that has defaults defined so they are not null

public class MyObj
{
  public IList<string> SomeList { get; set; }
    = new List<string>();
  ...
  // Other not-nullable properties
  ...
}

When I want to create a new instance, and initialize the values

var myListThatMightBeNull = GetMaybeNullList();
var newObj = new MyObj
{
  // assign other non-nullable properties
  SomeList = myListThatMightBeNull
};

Is there a clean way to assign the value to SomeList only if myListThatMightBeNull isn't null, and leave the default value otherwise?

Doing this obviously works, it just feels clunky compared to other modern syntax.

var newObj = new MyObj
{
  // assign other non-nullable properties
};

if (myListThatMightBeNull is not null)
{
  newObj.SomeList = myListThatMightBeNull;
}

Is there some sort of backwards =?? operator?

CodePudding user response:

You can use the null coalescing ?? operator while assigning this list. On the Microsoft website, you can find its documentation here

so you code will be as following:

var myListThatMightBeNull = GetMaybeNullList();
var newObj = new MyObj();
newObj.SomeList = myListThatMightBeNull ?? newObj.SomeList;

or if you need to use inline initialisation use empty list as default callback

var myListThatMightBeNull = GetMaybeNullList();
var newObj = new MyObj
{
    // assign other non-nullable properties
    SomeList = myListThatMightBeNull ?? new List<string>(),
};

CodePudding user response:

It's possible by using a full property:

public class MyObj
{
  private IList<string> _someList = new List<string>();

  public IList<string> SomeList
  {
    get => _someList;
    set => _someList = value ?? _someList;
  }
}

C# 12 (or later) might introduce a field keyword for property getters&setters, which will make it easier:

public class MyObj
{
  public IList<string> SomeList { get; set => field = value ?? field; }
}
  • Related