Call a method based on a parameter

  • Thread starter Thread starter Peter Kirk
  • Start date Start date
P

Peter Kirk

Hi there

in c# what is a good way of selecting which method to call based on a
string?

For example, my method can accept a string parameter (there are 50 or so
valid strings that can be passed in), and based on this string I should call
some other specific handler method.

Is there some smart mapping I can make between strings and methods? Some
sort of array like:

"string_one", method_1,
"string_two", method_2
etc

Then my method could match the the passed-in string with the array, and call
the appropriate method.


public void HandleData(string parameter)
{
// find string in array which matches parameter...
// call the associated method....
}


Thanks for any advice,
Peter
 
Peter said:
in c# what is a good way of selecting which method to call based on a
string?

For example, my method can accept a string parameter (there are 50 or so
valid strings that can be passed in), and based on this string I should call
some other specific handler method.

Is there some smart mapping I can make between strings and methods? Some
sort of array like:

"string_one", method_1,
"string_two", method_2
etc

You can do this very easily if all the methods you want to call have
the same signature, by using a delegate. Here's a sample (in .NET 2.0
which makes things slightly prettier, but it's the same principle in
..NET 1.1, just with more casting etc):

using System;
using System.Collections.Generic;

class Calculator
{
delegate int MathsOperation (int x, int y);

Dictionary<string, MathsOperation> lookup;

public Calculator()
{
lookup = new Dictionary<string, MathsOperation>();
lookup["+"] = Plus;
lookup["*"] = Times;
}

public int Compute (string op, int x, int y)
{
return lookup[op] (x, y);
}

int Plus (int x, int y)
{
return x+y;
}

int Times (int x, int y)
{
return x*y;
}
}

class Test
{
static void Main()
{
Calculator calculator = new Calculator();
Console.WriteLine (calculator.Compute ("+", 3, 5));
Console.WriteLine (calculator.Compute ("*", 10, 2));
}
}
 
Back
Top