471,627 Members | 2,166 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,627 software developers and data experts.

Call a method based on a parameter

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
Jan 26 '06 #1
2 1486
you can use string -> delegate map

Jan 26 '06 #2
Peter Kirk wrote:
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));
}
}

Jan 26 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by dennis luehring | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.