0

I have a function which accepts two base class parameters. Within this function I wish to test the types of these parameters over a number of derived classes and then call a polymorphic function. See below to see my first attempt which won't compile.

    public static double Intersect(baseClass s0, baseClass s1)
    {
          if (s1 is derivedClassB) return (s0 as derivedClassA).PolyMethod((derivedClassB)s1);

          else if (s1 is derivedClassC) return (s0 as  derivedClassA).PolyMethod((derivedClassC)s1);
                    else return 0.0;

    }

I thought i could use something like

Type dType = s0.GetType();
(s0 as dType).PolyMethod(derivedClassB) s1);

but this doesn't work either.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
gwizardry
  • 501
  • 1
  • 6
  • 19
  • Please format your code properly. – Simon Mar 17 '12 at 20:48
  • Sorry something went wrong in my attempted simplification...think its formatted ok now – gwizardry Mar 17 '12 at 20:53
  • Is there any reason you don't use the built-in support for polymorphic methods in C#? The *virtual* keyword? – Hans Passant Mar 17 '12 at 20:55
  • I have used virtual in my definition of the PolyMethod in my base class....this is just an issue in a single use static method which i'm using to handle the different types. I'm using virtual and override for PolyMethod – gwizardry Mar 17 '12 at 20:59

1 Answers1

2

Define your base class like this

public abstract BaseClass
{
    public abstract double PolyMethod(BaseClass s);
}

Define derived classes like this

public DerviedClassX : BaseClass
{
    public override double PolyMethod(BaseClass s)
    {
        return 0.0; // Return something usefull here.
    }
}

Then your method can be simplified like this

public static double Intersect(BaseClass s0, BaseClass s1)
{
    return s0.PolyMethod(s1);
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • I am not sure what you are trying to do here, however this [SO answer on virtual dispatch](http://stackoverflow.com/a/9165003/880990) and the link provided there to Eric Lippers arcticle on double dispatch might help you. – Olivier Jacot-Descombes Mar 17 '12 at 21:17
  • Thanks...simple when you know how. – gwizardry Mar 17 '12 at 21:19
  • No this is what i'm looking for...in fact my example is a little more complicated than what i presented here but i was just getting confused because i had two parameters varying over types. In fact it just boiled down to being this simple, working fine now. – gwizardry Mar 17 '12 at 21:22
  • OK. One note so. You can also use `virtual` methods instead of `abstract` methods, if the base class can provide a useful base implementation of the method. – Olivier Jacot-Descombes Mar 17 '12 at 21:25
  • Thanks, yes in this case it can't. I also realised i don't even need this static method I can just use s0.PolyMethod(s1) and have different methods for different (derivedClass) parameters s1. – gwizardry Mar 17 '12 at 21:45