C # 6 safe navigation not working in VS2015 preview

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 to form

    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 now unavailable?

+4
source share
2 answers

The type parent?.Xis float?that you add to float, which leads to another float?. It cannot be implicitly converted to float.

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

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

or

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

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

foo.X = foo.X;

... no-op, parent null X.

+8

null- null, parent null. , float NULL, float?.

:

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

null-coalescing , parent null.

0

Source: https://habr.com/ru/post/1569218/


All Articles