Why I cannot define both implicit and explicit operators like so?
public class C { public static implicit operator string(C c) { return "implicit"; } public static explicit operator string(C c) { return "explicit"; } }
You can do this hack though :)
class Program { public class A { } public class B { public static implicit operator A(B b) { Console.WriteLine("implicit"); return new A(); } } public class C : B { public static explicit operator A(C c) { Console.WriteLine("explicit"); return new A(); } } static void Main(string[] args) { C c = new C(); A a = c; A b = (A) c; } }
This prints:
implicit explicit
The Implicit Operator According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.
Use the operator and implicit or explicit keywords to define an implicit or explicit conversion, respectively. The type that defines a conversion must be either a source type or a target type of that conversion. A conversion between two user-defined types can be defined in either of the two types.
The operator used to perform cast operation in C# is parentheses. To perform a cast operation, the destination data type is explicitly written in parentheses before the value to be converted. An example for cast operation can be the conversion of a variable of double or float type to an integer type.
Check this: Why can't coexist implicit and explicit operator of the same type in C#?
If you define an explicit operator, you will be able to do something like this:
Thing thing = (Thing)"value";
If you define an implicit operator, you can still do the above, but you can also take advantage of implicit conversion:
Thing thing = "value";
In short, explicit allows only explicit conversion, while implicit allows both explicit and implicit... hence the reason why you can only define one.
I don't know the technical limitation that prevents this, but I think they would have done this to prevent people from shooting their own feet off.
string imp = new C(); // = "implicit" string exp = (string)new C(); // = "explicit"
That would drive me bonkers and makes no sense, C
should only cast to a string 1 way, not 2 different ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With