Extrakun
Extrakun

Reputation: 19325

.NET 4 - Using nullable operator (??) to simplify if statements

I have this piece of code, that checks whether a returned object is null. If so, it will return 0, or else it will return a property inside the object.

var userPoints = (from Point p in entities.Point
                 where p.UserName == userName
                 select p).SingleOrDefault();

        if (userPoints == null)
        {
            return 0;
        }
        else
        {
            return userPoints.Points;
        }

Is it possible to simplify the if statements with the nullable operator? I've tried this, but the system throws an exception when attempting to read the property

return userPoints.Points ?? 0;

Upvotes: 0

Views: 568

Answers (4)

Talljoe
Talljoe

Reputation: 14827

You can do this:

  var userPoints = (from Point p in entities.Point
                   where p.UserName == userName
                   select p.Point).SingleOrDefault();
  return userPoints;

If there are no results then userPoints will be 0, otherwise it will be the value of Points.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1501163

No, unfortunately there's nothing which will do exactly that. Options:

  • Use the conditional operator:

    return userPoints == null ? 0 : userPoints.Points;
    
  • Change your query to make that do the defaulting:

    return (from Point p in entities.Point
            where p.UserName == userName
            select p.Points).SingleOrDefault();
    

Personally I'd go for the latter approach :) If you wanted a default other than 0, you'd need something like:

return (from Point p in entities.Point
        where p.UserName == userName
        select (int?) p.Points).SingleOrDefault() ?? -1;

Upvotes: 2

satnhak
satnhak

Reputation: 9861

Hover over var with the mouse and see what type it is.

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

You can't use it in your context.
Explanation:
You want to check whether userPoints is null, but want to return userPoints.Points if it is not null.
The ?? operator checks the first operand for null and returns it, if it is not null. It doesn't work if what you want to check and what you want to return are two different things.

Upvotes: 0

Related Questions