cskwg
cskwg

Reputation: 849

Pick overloaded method as argument

namespace PickOverload;

class Program {

    delegate string Formatter( object o );

    string Show( double a ) { return a.ToString(); }

    string Show( int a ) { return a.ToString(); }

    string Format( Formatter f, object o ) { return f( o ); }

    void SelectArgument() {
        // error CS1503: Argument 1: cannot convert from 'method group' to 'Program.Formatter'
        Format( Show, 1.234 );
    }

    void SelectDelegate() {
        // error CS0123: No overload for 'Show' matches delegate 'Program.Formatter
        Formatter x = this.Show;
    }

    void Run() {
        SelectArgument();
        SelectDelegate();
    }

    static void Main( string[] args ) {
        new Program().Run();
    }
}

Is there a C# syntax for picking one of the overloaded Show methods as argument for the Format method or for the delegate?

I'm not looking for a solution for the above sample, but for ways to pick one of multiple overloaded methods for delegates or method arguments.

Same problem here:

void Run() { 
  double f = 1.234; 
  Format( Show, f ); 
  Formatter x = this.Show; 
} 

static void Main(string[] args ) { 
  new Program().Run(); 
}

Upvotes: 3

Views: 75

Answers (1)

DavidG
DavidG

Reputation: 118937

You can do this with generics, for example:

internal delegate string Formatter<T>(T o);

internal static string Show(double a) => a.ToString();
internal static string Show(int a) => a.ToString();

internal static string Format<T>(Formatter<T> f, T o) => f(o);

static void Main(string[] args)
{
    double f = 1.234;
    Format(Show, f);
}

Upvotes: 3

Related Questions