Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How C# support CallByName?

Reflection

How C# support CallByName?

by  xcduan  Posted    (Edited  )

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");

Console.ReadLine();
}

static void Main()
{
ClassA ca=new ClassA();
ca.Caller();
}
}
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top