How to call a generic function in an instance of a class?

Let's say I have two classes:

class Batman
{
    public void Robin(){...}
    public void Jump(){...}
}

class Superman
{
    public void Kryptonie(){...}
    public void Jump(){...}
}

Now I have an instance of these classes:

public object Crossover()
{
     var batman = new Batman();
     var superman = new Superman();

     return superman;
}

I do not know which instance will be returned by the crossover, it can be Batman or Superman.

var someVariableName = Crossover(); //I don't know if this contains an instance of Superman or Batman;

//I do know that no matter which class instance is returned, it will always contain a function named Jump which i want to trigger:
someVariableName.Jump();

Now I know that I can do something like:

if (someVariableName.GetType() == typeof(Superman)) 
{
    ((Superman) someVariableName).Jump()
}

But is there a way to call the transition function without having to manually check each type with if..else .. when I know that the instance of the class stored in this variable will always contain the transition function?

+4
source share
3 answers

This is where the interfaces become useful. Consider this interface:

public interface ISuperhero
{
    void Jump();
}

And these implementations:

class Batman : ISuperhero
{
    public void Robin(){...}
    public void Jump(){...}
}

class Superman : ISuperhero
{
    public void Kryptonie(){...}
    public void Jump(){...}
}

These are individual implementations, but they share a common polymorphic interface. Then your function can return this interface:

public ISuperhero Crossover()
{
     var batman = new Batman();
     var superman = new Superman();

     return superman;
}

Jump(), :

var someVariableName = Crossover();
someVariableName.Jump();
+3

:

interface ISuperHero
{
    void Jump();
}

class Batman : ISuperHero
{
    public void Robin(){...}
    public void Jump(){...}
}

class Superman : ISuperHero
{
    public void Kryptonie(){...}
    public void Jump(){...}
}

:

public ISuperHero Crossover()
+14

You can create a base class that defines a method (or an interface, if it is only a definition of a method). Then you can override the implementation in the output classes.

abstract class ActionFigure
{
    public abstract void Jump(); // just define it has a Jump method, but implement it in the deriving class

    public void SomethingGeneral()
    {
        // no need for an override, just implement it here
    }
}

class Batman : ActionFigure
{
    public void Robin(){...}
    public override void Jump(){...}
}

class Superman : ActionFigure
{
    public void Kryptonie(){...}
    public override void Jump(){...}
}
+3
source

All Articles