开发者

.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.Poi开发者_StackOverflownts;
        }

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;


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;


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜