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

8

10

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.

Homophile answered 11/4, 2010 at 5:52 Comment(1)
On the second, you're thinking of both the null coalescing operator and the conditional operator. Unfortunately, you've managed to combine them into illegal code. See the answers below for usage of the conditional operator.Pitapat
P
4

Your syntax on the second is slightly off.

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
Pitapat answered 11/4, 2010 at 5:57 Comment(0)
O
7

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 ?? "";
Odele answered 30/6, 2016 at 7:16 Comment(1)
What if username is an existing variable with already a value and you want to overwrite the value ONLY if SomeUserObject?.Username is not null otherwise leave the existing value. Is there another shorter way than username = SomeUserObject?.Username ?? username; ?Shows
P
4

Your syntax on the second is slightly off.

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
Pitapat answered 11/4, 2010 at 5:57 Comment(0)
S
2

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

string username = SomeUserObject == null ? null : SomeUserObject.Username;
Strohbehn answered 11/4, 2010 at 5:57 Comment(0)
J
1

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

string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
Josi answered 11/4, 2010 at 5:57 Comment(0)
S
1

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) ...

Slideaction answered 11/4, 2010 at 6:7 Comment(0)
D
1

This code will not assign the property in case the value is null. This is useful for when null has a special meaning of 'skip this property'.

public static void NullGuard<T>(Expression<Func<T>> expression, T? value)
{
    if (expression.Body is not MemberExpression memberExpression)
        throw new ArgumentException("Expression must be a member access expression.");

    var member = memberExpression.Member;

    if (member is not PropertyInfo property)
        throw new ArgumentException("Member must be a property.");

    if (value == null)
    {
        return;
    }

    var constant = Expression.Constant(value);
    var assignment = Expression.Assign(memberExpression, constant);
    var lambda = Expression.Lambda<Action>(assignment);

    lambda.Compile().Invoke();
}

Usage:

NullGuard(() => obj.SomeProperty, maybeNullValue);
Donella answered 29/4 at 3:29 Comment(1)
Good answer! You could do the value == null check as first to make it a tiny bit faster maybe.Guzzle
W
0

You're thinking of the ternary operator.

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

See http://msdn.microsoft.com/en-us/library/ty67wk28.aspx for more details.

Watercool answered 11/4, 2010 at 5:59 Comment(0)
R
-1

It is called null coalescing and is performed as follows:

string username = SomeUserObject.Username ?? ""
Raincoat answered 11/4, 2010 at 5:56 Comment(2)
Will still fail if SomeUserObject is null.Watercool
SomeUserObject could be null. He should be using the conditional operator and checking his object for null.Pitapat

© 2022 - 2024 — McMap. All rights reserved.