Reputation: 11523
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
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
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
Reputation: 16435
Yes, use a delegate. Which include Lambda Expressions and anonymous methods
Upvotes: 2