Hi everybody.
Can anyone tell me how can I implement Call By Name in C#?
I really have no idea about this.
Thanks for any advise.
views:
123answers:
3
+1
A:
You can do that using Reflection:
using System; using System.Reflection; class CallMethodByName { string name; CallMethodByName (string name) { this.name = name; } public void DisplayName() // method to call by name { Console.WriteLine (name); // prove we called it } static void Main() { // Instantiate this class CallMethodByName cmbn = new CallMethodByName ("CSO"); // Get the desired method by name: DisplayName MethodInfo methodInfo = typeof (CallMethodByName).GetMethod ("DisplayName"); // Use the instance to call the method without arguments methodInfo.Invoke (cmbn, null); } }
x3ro
2010-10-25 21:58:57
This is not call-by-name. http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_name
Ron Warholic
2010-10-25 22:00:20
The OP most likely refers to http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_name which is different from dynamically calling a method based on the name.
0xA3
2010-10-25 22:03:04
+1
A:
If you mean this, then I think the closest equivalent would be delegates.
Steven Sudit
2010-10-25 22:00:21
+4
A:
Pass a lambda function instead of a value. C# is eagerly evaluated so in order to defer execution so that each site re-evaluates the supplied arguments you need to wrap the arguments in a function.
int blah = 1;
void Foo(Func<int> somethingToDo) {
int result1 = somethingToDo(); // result1 = 100
blah = 5;
int result2 = somethingToDo(); // result = 500
}
Foo(() => blah * 100);
You can use the Lazy class if you're in .NET 4.0 to get a similar (but not identical) effect. Lazy
memoizes the result so that repeated accesses do not have to re-evaluate the function.
Ron Warholic
2010-10-25 22:09:12
To those who are wondering, using `Lazy<T>` will result in *call-by-need*.
Porges
2010-10-25 22:32:03
@Steven: Indeed, however strictly speaking lambdas are not delegates but implicitly convertible to matching delegate types.
Ron Warholic
2010-10-25 22:43:48
That distinction would matter if we were to manipulate it as an expression tree, but doesn't happen to make any difference here.
Steven Sudit
2010-10-25 22:50:58