Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • 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!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


C# (C sharp): Microsoft FAQ


How C# support CallByName? by xcduan
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);
            Console.WriteLine("Wrong Function Name");


      static void Main()
         ClassA ca=new ClassA();

Back to C# (C sharp): Microsoft FAQ Index
Back to C# (C sharp): Microsoft Forum

My Archive

Close Box

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:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close