How to properly check and handle null values or objects

   var userDomain = (from a in this.db.DomainList.ToList()
                            join b in this.db.UserDomain.ToList() on a.DomainId equals b.UserDomainId
                            where b.UserId == new System.Guid(user.ProviderUserKey.ToString())
                            select new
                            {
                                a.DomainId,
                                a.DomainName
                            }).FirstOrDefault();

string userDomainName = (userDomain.DomainName ?? "None").ToString(CultureInfo.InvariantCulture);

I have the above sample code. When userDomain is null, i want to set userDomainName varibale to "None" else if userDomain is not null, userDomainName variable should be set to userDomain.DomainName

I have tried below line of code

 string userDomainName = (userDomain.DomainName ?? "None").ToString(CultureInfo.InvariantCulture);

but that does't work as it throws error

Object reference not set to an instance of an object.

if userDomain is null.

Jon Skeet
people
quotationmark

Yes, if userDomain is null, then

userDomain.DomainName

will fail.

In C# 6, you can get over this with the null conditional operator:

string userDomainName = userDomain?.DomainName ?? "None";

Before C# 6, you need:

string userDomainName = 
    (userDomain == null ? null : userDomain.DomainName) ?? "None";

That's assuming it's possilble for userDomain to be non-null and userDomain.DomainName to be null - if it's not, you could just use:

string userDomainName = userDomain == null ? "None" : userDomain.DomainName;

Note that you don't need the ToString part - calling ToString(CultureInfo.InvariantCulture) on a string will never change it.

people

See more on this question at Stackoverflow