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 accessibility
compiler 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?