2
votes

I have a struct with the following operator declared :

public struct myStruct {
    public static implicit operator int(Nullable<myStruct> m){
        /*...*/
    }
}

This operator alone lets me implicitly convert a non-nullable struct to int, but trying to implicitly convert its nullable counterpart still raises a compilation error :

Cannot implicitly convert type myStruct? to int. An explicit conversion exists (are you missing a cast?)

Apparently the mentioned "explicit" operator is actually the implicit operator I declared, removing this operator altogether also removes the mention of the explicit one.

When it comes to nullable structs, why am I being forced to use this operator explicitly even though it was declared implicit?


EDIT:
So here is the "full code", stripped of everything that doesn't make the compiler error disappear. The struct stays literally the same, all that's new is my testing code :

using System;

public struct boilDown {
    public static implicit operator int(Nullable<boilDown> s) { return 0; }
} // END Struct

public class Sandbox {
    void Update ()
    {
        boilDown nonNullable = new boilDown ();
        Nullable<boilDown> NullableVersion = new Nullable<boilDown>();

        int MyInt;
        MyInt = nonNullable;        // this work thanks to my operator
        MyInt = NullableVersion;    // But this line requires an explicit cast
    }
}

VERSION :
You all hinted me at a c# version issue. I'm working on Unity 2017.1.0f3, which rather than .Net, uses Mono 2.0.50727.1433. (This apparently is a NET3.5 Equivalent, but even their experimental NET4.6 equivalent has this issue.)
I'll ask this question to them and see what they say.

2
Try it with "int?" - Voodoo
Give us entire code. - apocalypse
Full code coming right up. After boiling it down to the bug, there isn't anything new to see in the struct itself, only the testing code. - Estecka
what version of C#? Console-App 4.6.1 is fine with it, no errors or warnings. - Patrick Artner
dotnetfiddle.net with 4.5 - fine as well... - Patrick Artner

2 Answers

1
votes

You could explicitly cast the NullableVersion to int like below.

using System;

public struct boilDown {
    public static implicit operator int(Nullable<boilDown> s) { return 0; }
} // END Struct

public class Sandbox {
    static void Main()
    {

    }
    void Update ()
    {
        boilDown nonNullable = new boilDown ();
        Nullable<boilDown> NullableVersion = new Nullable<boilDown>();

        int MyInt;
        MyInt = nonNullable;        // this work thanks to my operator
        MyInt = (int)NullableVersion;    // works now
    }
}
1
votes

Thanks all who told me this code should compile.
Unity confirmed this error to be a bug on their end.