Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value of a property to a var ONLY if the object isn't null

Tags:

c#

null

In my code, is there a shorthand that I can use to assign a variable the value of a object's property ONLY if the object isn't null?

string username = SomeUserObject.Username;     // fails if null

I know I can do a check like if(SomeUserObject != null) but I think I saw a shorthand for this kind of test.

I tried:

string username = SomeUserObject ?? "" : SomeUserObject.Username;

But that doesn't work.

like image 596
Blankman Avatar asked Apr 11 '10 05:04

Blankman


People also ask

How do you know if something returns null?

To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.

How do you make a variable not null in Java?

Using the not equal operator ( variable != null ) Using the Objects class nonNull() method.

IS null condition C#?

The null conditional is a form of a member access operator (the .). Here's a simplified explanation for the null conditional operator: The expression A?. B evaluates to B if the left operand (A) is non-null; otherwise, it evaluates to null.


5 Answers

Your syntax on the second is slightly off.

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
like image 90
Anthony Pegram Avatar answered Oct 23 '22 14:10

Anthony Pegram


In c# 6.0 you can now do

string username = SomeUserObject?.Username;

username will be set to null if SomeUSerObject is null. If you want it to get the value "", you can do

string username = SomeUserObject?.Username ?? "";
like image 3
Philip Avatar answered Oct 23 '22 16:10

Philip


The closest you're going to get, I think, is:

string username = SomeUserObject == null ? null : SomeUserObject.Username;
like image 2
Michael Petrotta Avatar answered Oct 23 '22 14:10

Michael Petrotta


This is probably as close as you are going to get:

string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
like image 1
Taylor Leese Avatar answered Oct 23 '22 14:10

Taylor Leese


You can use ? : as others have suggested but you might want to consider the Null object pattern where you create a special static User User.NotloggedIn and use that instead of null everywhere.

Then it becomes easy to always do .Username.

Other benefits: you get / can generate different exceptions for the case (null) where you didn't assign a variable and (not logged in) where that user isn't allowed to do something.

Your NotloggedIn user can be a derived class from User, say NotLoggedIn that overrides methods and throws exceptions on things you can't do when not logged in, like make payments, send emails, ...

As a derived class from User you get some fairly nice syntactic sugar as you can do things like if (someuser is NotLoggedIn) ...

like image 1
Ian Mercer Avatar answered Oct 23 '22 14:10

Ian Mercer