Search code examples
c#.net.net-3.5subtype

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?


Solution

  • An interface. Change your method signature to

    myMethod(ICastableAsMyBaseClass mbc)
    

    Then have ot1 and ot3 implement ICastableAsMyBaseClass.