Matt
Matt

Reputation: 26971

Accepting a limited set of subtypes in a method argument

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?

Upvotes: 1

Views: 131

Answers (2)

Joel
Joel

Reputation: 19358

An interface. Change your method signature to

myMethod(ICastableAsMyBaseClass mbc)

Then have ot1 and ot3 implement ICastableAsMyBaseClass.

Upvotes: 5

sepp2k
sepp2k

Reputation: 370122

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.

Upvotes: 2

Related Questions