INTELLIGENT WORK FORUMS FOR COMPUTER PROFESSIONALS
Come Join Us!
Are you a Computer / IT professional? Join Tek-Tips now!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts
- Keyword Search
- One-Click Access To Your
Favorite Forums
- Automated Signatures
On Your Posts
- Best Of All, It's Free!
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.
Partner With Us!
"Best Of Breed" Forums Add Stickiness To Your Site

(Download This Button Today!)
Feedback
"...Since using forums in my early days 10 years ago in CompuServe, one had to log back on and sometimes wait days for a response. Now I get a response e-mailed to me which I can click a link and go right back to exactly where My post was..."
Geography
Where in the world do Tek-Tips members come from?
|
C# (C sharp): Microsoft FAQ
|
Reflection
|
How C# support CallByName?
Posted: 28 May 02
|
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(); } } }
|
Back to C# (C sharp): Microsoft FAQ Index
Back to C# (C sharp): Microsoft Forum |
|
 |
|
Join Tek-Tips® Today!
Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.
Here's Why Members Love Tek-Tips Forums:
Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More...
Register now while it's still free!
Already a member? Close this window and log in.
Join Us Close