danmine
danmine

Reputation: 11523

Is it possible to declare a method as a parameter in 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.

Upvotes: 4

Views: 222

Answers (5)

csharptest.net
csharptest.net

Reputation: 64248

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); });

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564861

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";
    }
 });

Upvotes: 21

Sterno
Sterno

Reputation: 1658

I think you're looking for a delegate.

Upvotes: 1

Chuck Conway
Chuck Conway

Reputation: 16435

Yes, use a delegate. Which include Lambda Expressions and anonymous methods

Upvotes: 2

dove
dove

Reputation: 20692

anonymous methods

Upvotes: 2

Related Questions