views:

57

answers:

2

This is with C# and .net 3.5

Let's say I have the following method:

myMethod(myBaseClass mbc)

In my project, all the following classes inherit from myBaseClass.

ot1:myBaseClass
ot2:myBaseClass
ot3:myBaseClass
ot4:myBaseClass

Are there any tricks that will let me use myMethod with ot1 and ot3 but NOT ot2 and ot4, or do I basically have to overload for each type I want to allow?

+2  A: 

You could check the class of mbc at runtime, but obviously that would not prevent you from calling the method with the wrong time at compile-time.

If you want compile-time typechecking you need to overload the method for each type you want to allow.

sepp2k
With this particular solution you can just delegate both constructors to a private constructor that takes the base type. Now you get compile time safety and don't have to duplicate the constructor.
KeeperOfTheSoul
+5  A: 

An interface. Change your method signature to

myMethod(ICastableAsMyBaseClass mbc)

Then have ot1 and ot3 implement ICastableAsMyBaseClass.

Joel Potter
That wouldn't prevent classes not deriving from MyBaseClass from implementing the interface though. He could make it generic like that: myMethod<T>(T mbc) where T: MyBaseClass, ICastableAsMyBaseClass
Botz3000
That's not a bad idea.
Joel Potter