Search code examples
c#asp.net.netbooleannon-nullable

Assign non nullable value in boolean only if its non null


I have a object that has a boolean field called NameIndicator (External contract one). In my code, I made the my boolean "IsIndicated" as nullable.

How do I check for null and assign value only if non null?

I currently get compile time error with the below code as obvious its assining nullable to non nullable field

 personDetails.Name= new Name_Format()
                    {
                        NameSpecified = true,
                        NameIndicator = contract.IsIndicated
                    };

Solution

  • If you want to assign a particular value in the case of null, and the value otherwise, you use the null coalescing operator.

    personDetails.Name= new Name_Format()
    {
      NameSpecified = true,
      NameIndicator = contract.IsIndicated ?? true
    };
    

    That has the same semantics as

    personDetails.Name = new Name_Format()
    {
      NameSpecified = true,
      NameIndicator = contract.IsIndicated == null ? true : contract.IsIndicated.Value
    };
    

    except that of course it only calls IsIndicated once.

    If you want the runtime to choose a default value for you then you can do

    personDetails.Name = new Name_Format()
    {
      NameSpecified = true,
      NameIndicator = contract.IsIndicated.GetValueOrDefault()
    };
    

    In this case it will choose "false", since that is the default value for Booleans.

    If you want nothing at all to happen if the value is null then you can use an if statement:

    if (contract.IsIndicated != null)
    {
      personDetails.Name = new Name_Format()
      {
        NameSpecified = true,
        NameIndicator = contract.IsIndicated.Value
      }
    };