Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 6 safe navigation not working in VS2015 preview

Tags:

c#

roslyn

c#-6.0

I have the following property in my code

public float X {
    get {
        if (parent != null)
            return parent.X + position.X;
        return position.X;
    }
    set { position.X = value; }
}

I was hoping to convert the getter into the form of

    get {
        return parent?.X + position.X;
    }

But I get the following error: Cannot implicitly convert type 'float?' to 'float'. An explicit conversion exists (are you missing a cast?)

Am I doing something wrong or is it not available right now?

like image 500
Nicolas Martel Avatar asked Feb 12 '23 06:02

Nicolas Martel


1 Answers

The type of parent?.X is float?, which you're adding to a float - resulting in another float?. That can't be implicitly converted to float.

While Yuval's answer should work, I would personally use something like:

get
{
    return (parent?.X ?? 0f) + position.X;
}

or

get
{
    return (parent?.X).GetValueOrDefault() + position.X;
}

I'm not sure of your design, mind you - the fact that you add something in the getter but not in the setter is odd. It means that:

foo.X = foo.X;

... will not be a no-op if parent is non-null with a non-zero X value.

like image 186
Jon Skeet Avatar answered Feb 13 '23 20:02

Jon Skeet