Reputation: 3175
I would like to do something like this:
public static void Initialize<T>(T obj) where T : BaseClass
{
SetDefault(obj);
}
private static void SetDefault(AInheritedFromBaseClass thing)
{
// do something
}
private static void SetDefault(BInheritedFromBaseClass thing)
{
// do something
}
So everytime I initialize the obj it is directed to the correct method. Is that possible?
I can not implement those methods on the classes it self, because they are external classes. So basically I'd like to have a gereric way to initialize them they way I want to. I'd like to avoid something like this:
if (obj is TypeA)
{
ClassThis();
} else if (obj is TypeB)
{
CallThat();
}
//etc.
Upvotes: 2
Views: 61
Reputation: 68660
If they're external classes and you need to modify the way they are initialized, I'd go with something like the Adapter pattern, instead of coming up with workarounds.
Also, your solution will crash at runtime if you ever like adding a third BaseClass
implementation and forget to add another SetDefault
overload. You shouldn't rely on that.
Upvotes: 0
Reputation: 125630
Use dynamic
:
public static void Initialize<T>(T obj) where T : BaseClass
{
SetDefault((dynamic)obj);
}
It will force your method overload selection happen on runtime instead of compile time.
Upvotes: 7