Phoenix
Phoenix

Reputation: 913

Method overrides with Func<T,M> and Action<T> in C#

I have the following two methods which work:

    public T InvokeFunc<T>(Func<ServiceClient,T> operation)
    {
        return operation(client);
    }

    public void InvokeAction(Action<ServiceClient> operation)
    {
        operation(client);
    }

Is there a way to make these methods override each other, with the compiler being able to distinguish which one I am trying to use?

This is what I have tried:

    public void InvokeOperation(Action<RimsoftHRServiceClient> operation)
    {
        operation(client);
    }

    public T InvokeOperation<T>(Func<RimsoftHRServiceClient,T> operation)
    {
        operation(client);
    }

but when I try to use any of the two methods I get an error saying the compiler can't recognize which method I want to use.

I want to do something like this:

 List<City> cities = InvokeOperation(x => x.GetAllCities()); //GetAllCities returns List<City>

But also be able to do this too:

InvokeOperation(x=>x.TestCommunication()); //TestCommunication returns void

Is that possible or do I have to use different names for both methods?

Upvotes: 1

Views: 627

Answers (1)

Unfortunately it is not possible to do this .

The specification states that C # Methods Overloaded must have different parameters , as seen in the link below ,

http://msdn.microsoft.com/en-us/library/ms229029.aspx

It makes sense , after all, how would he know which method you are using before being compiled ? This could generate an exception at runtime

Hope this helps

Upvotes: 1

Related Questions