Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a method as a parameter in C#?

Tags:

c#

For example the main method I want to call is this:

public static void MasterMethod(string Input){
    /*Do some big operation*/
}

Usually, I would do something like this this:

public static void StringSelection(int a)
{
    if(a == 1)
    {
       return "if";
    }
    else
    {
       return "else";
    }
}

MasterMethod(StringSelection(2));

But I want to do something like this:

MasterMethod( a = 2
     {
        if(a == 1)
        {
           return "if";
        }
        else
        {
           return "else";
        }
     });

Where 2 is somehow passed into the operation as an input.

Is this possible? Does this have a name?

EDIT:: Please note, the MasterMethod is an API call. I cannot change the parameters for it. I accidentally made a typo on this.

like image 750
danmine Avatar asked Nov 27 '22 15:11

danmine


2 Answers

You can do this via delegates in C#:

public static string MasterMethod(int param, Func<int,string> function)
{
    return function(param);
}


// Call via:
string result = MasterMethod(2, a => 
{
    if(a == 1)
    {
       return "if";
    }
    else
    {
       return "else";
    }
 });
like image 75
Reed Copsey Avatar answered Dec 15 '22 07:12

Reed Copsey


You can do this with anon delegates:

    delegate string CreateString();

    public static void MasterMethod(CreateString fn)
    {
        string something = fn();
        /*Do some big operation*/
    }

    public static void StringSelection(int a)
    {
        if(a == 1)
        {
           return "if";
        }
        else
        {
           return "else";
        }
    }

    MasterMethod(delegate() { return StringSelection(2); });
like image 29
csharptest.net Avatar answered Dec 15 '22 07:12

csharptest.net