I\'m trying to write generic method to cast types. I want write something like Cast.To
instead of (Type) variable
.
My wrong versi
All of what's been said about the operator resolution is correct...but this is my answer to your main question:
public static T To(this object o)
{
return (T)(dynamic)o;
}
The key here is that casting o to dynamic will force the .NET to search for the explicit operator at runtime.
Plus, why not make it an extension method?
Instead of
A a = new A();
B b = Cast.To(a);
you can do
A a = new A();
B b = a.To();
An added benefit of exposing it as an extension method is that you gain a fluent interface for explicit casting (if you like that sort of thing). I've always hated the amount of nested parenthesis balancing required for explicit casting in .NET.
So you can do:
a.To().DoSomething().To().DoSomethingElse()
instead of
((C)((B)a).DoSomething())).DoSomethingElse()
which, to me, looks clearer.