Reputation: 15648
Why does implicit operator have problems when I try to convert the return type to an object or a one custom type that I have defined myself?
I have no problem when I am trying to convert and return a simple type like an int
, like this
public static implicit operator int(MyClass a)
{
return 123;
}
However, when I try to convert the type into an object or a custom type, I will get an error. For example, I will get a compile-time error saying "User-defined conversion to System.Object" if I have something like this:
public static implicit operator object(MyClass a)
{
return new {};
}
I will get the same kind of error if I have this:
public static implicit operator CustomTestObject(MyClass a)
{
return new CustomTestObject();
}
How can I convert it to my own custom defined type for return when using an implicit operator?
Upvotes: 0
Views: 938
Reputation: 61950
You cannot declare an implicit conversion to one of your own base classes. System.Object
is always your (direct or indirect) base class. Through inheritance there's already an implicit conversion to the base class. So how could there be two implicit conversions? The C# spec has a good reson to disallow this!
Upvotes: 5