In an application, I need .NET to call a method based on its run-time type instead of its compile-time type.
Simplified Example:
class A { }
class B : A { }
static void Main(string[] args)
{
A b = new B();
Print(b);
}
static void Print(A a)
{
Console.WriteLine("Called from A");
}
static void Print(B b)
{
Console.WriteLine("Called from B");
}
The above code will actually print Called from A
, but I need it to be Called from B
.
This works as expected:
static void Print(A a)
{
var b = a as B;
if (b != null)
return Print(b);
else
Console.WriteLine("Called from A");
}
But for maintainability's sake, it is not desirable.
I believe this question is similar to this one: Why isn't this method chosen based on the runtime-type of its object?, but for .NET instead of Java.
The simplest approach if you're using .NET 4 or higher is to use dynamic typing:
dynamic b = new B();
Print(b);
Almost all expressions using a value of type dynamic
will be invoked dynamically, with a "mini-C# compiler" applying the same rules at execution time as it would have done at compile-time, but using the actual execution-time type of those dynamic values. (Expressions whose types are known statically at compile-time will still be regarded as having those types though - it doesn't make everything about overload resolution into dynamic.)
If you're not using .NET 4, it's somewhat harder - you could either use reflection, or hard-code the options, neither of which is fun.
You can make use of the dynamic
type:
A b = new B();
dynamic tmp = b;
Print(tmp); // Prints "Called from B"
However, please note that this has the draw back that it will generate a runtime exception instead of a compile error if there is no matching method.
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