Home:ALL Converter>C# why must conversion operator must be declared static and public?

C# why must conversion operator must be declared static and public?

Ask Time:2014-07-29T02:13:07         Author:Philip Pittle

Json Formatter

Regarding the following compiler error:

User-defined operator 'Foo.implicit operator Foo(Bar)' must be declared static and public

What is the reason for this? Why must a user-defined conversion operator be public?

Give the following code, why wouldn't this conversion be legal:

 internal class Bar{}

 internal class Foo
 {
     private Bar _myBar;

     internal static implicit operator Bar(Foo foo)
     {
          return foo._myBar;
     } 
 }

I checked the C# Language Spec and the relevant section (10.10.3) didn't mention this requirement. Is it a compiler thing and not a C# / .Net restriction?

To make things weirder, I can make the above conversion operator public as long as both Foo and Bar are internal, which is odd, because I would think that you couldn't return an internal object on a public method (although I suppose if the entire class is internal it wouldn't matter). However, if I make a public PublicFoo and keep Bar internal then I get an inconsistent accessibilitycompiler error:

internal class Bar { }

internal class Foo
{
    private Bar _myBar;

    /// <summary>
    /// No inconsistent accessibility: return type
    /// </summary>
    public static implicit operator Bar(Foo foo)
    {
        return foo._myBar;
    }
}

public class PublicFoo
{
    private Bar _myBar;

    /// <summary>
    /// Inconsistent accessibility: return type !!
    /// </summary>
    public static implicit operator Bar(PublicFoo foo)
    {
        return foo._myBar;
    }
}

Summary

Why must user-defined conversions be public?

Author:Philip Pittle,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/25001580/c-sharp-why-must-conversion-operator-must-be-declared-static-and-public
yy