Reputation: 21265
I'll start by I have no idea on the terminology on this or if it is even possible (I am pretty sure it can be done).
I have a chunk of code that is basically as follows:
DataTable dt = new DataTable();
if (string = "this")
dt = method1();
else if (string = "that")
dt = method2();
else if (string = "somethingelse")
dt = method3(datetime, datetime2);
else if (string = "anotherthing")
dt = method4(string);
....and so on....
I am trying to make this cleaner. The comparison string is in a table. My thought would be to do something more like the following:
if (row.parmtype = "date"){
dt = row.method(datetime, datetime2);
else
dt = row.method();
So the method I call would be stored in the table along with the type of call it is (there are only 3 types so far). Each call returns a DataTable. Can I either get a sample for better yet, a resource on how to do this?
Realize that since I don't know what I am talking about, the above code isn't exactly what I am looking for, but is for the purpose of getting my point across.
Upvotes: 1
Views: 131
Reputation: 8008
you can do a dictionary like
var delegates = new Dictionary<string, Func<MyClass, DataTable>>()
{
{"somestr", x => x.Method1()}
};
if (delegates.ContainsKey(key))
delegates[key](this);
Upvotes: 2
Reputation: 21141
You have a couple of options (off the top of my head) that work in basically any version of the framework:
Any of these should work depending on your requirements, the simplest "next step" from where you are is to probably change to a switch statement and then look at using the command pattern. Reflection can be great, but expensive if you are doing it at a high volume and you dont take care to use good caching. Fasterflect can help if you decide to go this direction.
In .NET 4.0 (maybe 3.5) you could also look at using dynamic and expression trees to do something similar, but this may be more code than you want to write for your current implementation.
Upvotes: 1