I’d like to create some helper methods that are inheritance aware. I’d like them to work like virtual + override methods, yet without having to define a class hierarchy.
Here’s how it might work with a cast. I’d like to be able to do this without the performance his of having multiple casts… and without defining yet another hierarchy:
class Program {
static void Main(string[] args){
var a = new A();
var b = new B();
var h = new Helper();
h.DoSomething(a);
h.DoSomething(b);
}
}
public class A{}
public class B : A{}
public class Helper{
public void DoSomething(A o){}
public void DoSomething(B o){
DoSomething((A)o);
}
}
Any thoughts. Thanks in advance.
There’s no performance penalty in having a cast from
BtoA– it’s guaranteed to be correct, so there’s no actual check to be performed. It’s just delegating the method call.Having said that, I’d actually recommend against using overloads with type hierarchies like this. Overloading can get pretty complicated…
(And as ever, don’t assume a performance penalty without testing. Create a clean design, and test the performance. Only start bending things out of shape when you’ve found a problem.)