简体   繁体   中英

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
                    };

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
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM