CallByName in C#????

  • Thread starter Thread starter Jelle van Baardewijk
  • Start date Start date
Hi,

What?
Calling a method by its name?
Yes, it is possible - see reflection's MethodInfo class.
 
Reflection is one way to do it, but you can also use the VB version by
simply adding a reference to the visual basic namespace.

Yves
 
What is "callbyname" ?

It's from VB6. It allows you to execute methods on an object based on
the "name" of the method. It's basically late-binding, but the method
name may not be known at design-time. The code determines the method to
call and uses the CallByName function to dynamically make the call.
 
Patrick Steele said:
It's from VB6. It allows you to execute methods on an object based on
the "name" of the method. It's basically late-binding, but the method
name may not be known at design-time. The code determines the method to
call and uses the CallByName function to dynamically make the call.

Yeah, thanks, it seems that reflection can handle this sort of things, right?
 
Carsten Posingies said:
Just for couriousity, could you point me to an example in C#?

Yup:

using System;
using System.Reflection;

class Test
{
string name;

public Test (string name)
{
this.name=name;
}

public void PrintGreeting(string other)
{
Console.WriteLine ("{0} greets {1}", name, other);
}

static void Main()
{
Test t = new Test("Jon");
MethodInfo method = typeof(Test).GetMethod("PrintGreeting");

method.Invoke (t, new object[]{"Carsten"});
}
}
 
Jon said:
Carsten Posingies said:
Just for couriousity, could you point me to an example in C#?
Yup:

MethodInfo method = typeof(Test).GetMethod("PrintGreeting");

method.Invoke (t, new object[]{"Carsten"});

Argh! *blush* Same as one can call a JScript's method from within C#
code when tampering with the script engine.

If there was a way to "compound" GetMethod() and Invoke(), we would have
had something similar to JScript's eval()... If there wasn't the word
"if"... <g>

Thanks!
 
Thnx Guys,

This is what I needed:

public static void SetControlProperty(Control control, string propertyName,
object propertyValue)
{
Type myType = control.GetType();
PropertyInfo myInfo = myType.GetProperty(propertyName);
myInfo.SetValue(control, propertyValue, null);
}


Carsten Posingies said:
Jon said:
Carsten Posingies said:
Just for couriousity, could you point me to an example in C#?
Yup:

MethodInfo method = typeof(Test).GetMethod("PrintGreeting");

method.Invoke (t, new object[]{"Carsten"});

Argh! *blush* Same as one can call a JScript's method from within C#
code when tampering with the script engine.

If there was a way to "compound" GetMethod() and Invoke(), we would have
had something similar to JScript's eval()... If there wasn't the word
"if"... <g>

Thanks!
 
Back
Top