Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Lets say like this:

CallFunction("FunctionName", arrParams);

// Will get the function by name
Public FunctionName(object[] arrParams)
{

}
Posted
Updated 23-Aug-10 9:17am
v2

Yes, why not.
Use Reflection.

Type mytype = abc.GetType();
MethodInfo info = mytype.GetMethod("FunctionName");
info.Invoke(abc, params);



Where abc is the actual object that has the function FunctionName in it. :rose:
 
Share this answer
 
Comments
Roger Wright 24-Aug-10 0:04am    
Reason for my vote of 5
Nicely said!
The previous answer is correct. Just thought I'd add that you can also create a delegate to store a "pointer" to a function. You can pass that around just like any other variable. Here is an example:
C#
// The class with the function.
public class MyClass
{
    
    // The function you want to call.
    public int FunctionName(int val1, int val2)
    {
        return val1 + val2;
    }
    
}

// A class that interacts with MyClass.
public class SomeOtherClass
{
    
    // Defines the method signature.
    private delegate int IntDelegate(int val1, int val2);
    
    // A variable to hold the function.
    private IntDelegate storedFunction = null;
    
    // Grabs a reference to the function and stores it for later use.
    public void StoreFunctionPointer(MyClass myInstance)
    {
        storedFunction = myInstance.FunctionName;
    }
    
    // Calls the stored function.
    public int CallStoredFunction(int val1, int val2)
    {
        return storedFunction(val1, val2);
    }
    
}

If you wanted, you could then store those function pointers in a dictionary to look them up using a string key.
 
Share this answer
 
Comments
Roger Wright 24-Aug-10 0:05am    
Reason for my vote of 5
Quite a useful tip!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900