duo
duo

Reputation: 11

c# generic function for overloaded methods

I have two methods, FollowForce() and AvoidForce() which are overloaded to accept either a NavObject or a GameObject. Is there a way to simplify the Follow() function to accept both types?

public void Follow(NavObject target){ 
        if(isFollowing){Body.AddForce(FollowForce(target));}
        if(isAvoiding){Body.AddForce(AvoidForce(target));}
    }

public void Follow(GameObject target){ 
        if(isFollowing){Body.AddForce(FollowForce(target));}
        if(isAvoiding){Body.AddForce(AvoidForce(target));}
    }

I tried the following, but got cannot convert 'T' expression to type 'NavObject':

public void Follow <T>(T target){ 
        if(isFollowing){Body.AddForce(FollowForce(target));}
        if(isAvoiding){Body.AddForce(AvoidForce(target));}
    }

Upvotes: 1

Views: 79

Answers (3)

krillgar
krillgar

Reputation: 12815

Potentially, you don't even need to use Generics with this. You could also create an interface for your NavObject and GameObject to implement that contains all of the properties/methods that are needed within your FollowForce and AddForce methods.

public void Follow(IHaveForce target)
{
    if (isFollowing)
    {
        Body.AddForce(FollowForce(target));
    }
    if (isAvoiding)
    {
        Body.AddForce(AvoidForce(target));
    }
}

Then your other methods would need to be set up like this:

public Force FollowForce(IHaveForce target)
{
    // Do your work...
}

public Force AvoidForce(IHaveForce target)
{
    // Do your work...
}

The only reason you would need to utilize Generics would be if you want to enforce the same type throughout. In the minimal scenario you have provided, it doesn't seem as though that's what you need. If you want to use Generics anyway, you can have your Generic type implement IHaveForce as well.

Upvotes: 2

Juergen
Juergen

Reputation: 151

If your Objects share functionality you should introduce an abstract base class or an interface TrackedObject and extend them in your NavObject and GameObject. You then can write the following

public void Follow(TrackedObject target){ 
    if(isFollowing){Body.AddForce(FollowForce(target));}
    if(isAvoiding){Body.AddForce(AvoidForce(target));}
}

Your static functions parameters of FollowForce and AvoidForce must then also be of type TrackedObject

Upvotes: 0

J. D.
J. D.

Reputation: 1561

Your FollowForce and AvoidForce functions that are accepting target as a parameter must also accept type "T"

Upvotes: 1

Related Questions