views:

123

answers:

3

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.

+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
This is not call-by-name. http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_name
Ron Warholic
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
+1  A: 

If you mean this, then I think the closest equivalent would be delegates.

Steven Sudit
delegates? can you explain how?! do you mean, just using a delegate?
Dr TJ
Ron Warholic's example is an example of a delegate.
Steven Sudit
+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
To those who are wondering, using `Lazy<T>` will result in *call-by-need*.
Porges
A lambda function is one way to generate a `delegate`.
Steven Sudit
@Steven: Indeed, however strictly speaking lambdas are not delegates but implicitly convertible to matching delegate types.
Ron Warholic
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