VB supports CallByName. Does C# support that? How?
The answer to the first question is YES.
Suppose we have a class called ClassA that contains three methods: Function1(), Function2() and Caller(). We want Caller() to call either Function1() or Function2() at running time. By using Reflection technique provided by .NET, we can store the name of the function we need to call in a string variable and invoke the call using the string variable. Please see the source code attached.
NOTE: The methods to call must be public for this approach to work!!!
//**************************************
//
// CallByName Example
// Xiaochang Duan
// Dynamic Info Solution, LLC
// Contact: xcduan@yahoo.com
// 5/27/2002
//
//**************************************
using System;
using System.Reflection;
namespace CallByName
{
public class ClassA
{
//NOTE: Must be public function to be called by name.
public void Function1()
{
Console.WriteLine("Function1 is called.");
}
//NOTE: Must be public function to be called by name.
public void Function2()
{
Console.WriteLine("Function2 is called.");
}
private void Caller()
{
//The string variable holding the function name.
string FunctionName="Function1";
Type t=this.GetType();
MethodInfo mi=t.GetMethod(FunctionName);
if (mi!=null)
mi.Invoke(this, null);
else
Console.WriteLine("Wrong Function Name");
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.