Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a common function in a class instance? [duplicate]

Tags:

c#

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 those classes:

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

     return superman;
}

I do not know instance of which class the Crossover will return, it could 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 i could do something like:

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

But is there a way to trigger the Jump function without having to manually check for each type with if..else.., when i know that the instance of the class saved in that variable will always contain a Jump function?

like image 770
Fred Avatar asked Dec 01 '22 01:12

Fred


2 Answers

Use an interface:

interface ISuperHero
{
    void Jump();
}

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

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

Then return the interface from your method:

public ISuperHero Crossover()
like image 59
John Koerner Avatar answered Dec 18 '22 20:12

John Koerner


This is where 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(){...}
}

They're individual implementations, but they share a common polymorphic interface. Your function can then return that interface:

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

     return superman;
}

Since that interface has a Jump() method, it can be called directly:

var someVariableName = Crossover();
someVariableName.Jump();
like image 35
David Avatar answered Dec 18 '22 21:12

David