Hi,
I'm looking for a way to iterate through all methods in a class and run each method with values from an array. Thanks for the help
Iterate through methods
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
AlanRank #669 · 3.6K reputationPosted Apr 4, 2008, 1:22 AM EDT
Here's a quick program to show how you can call every method in a class (apart from the constructor) using reflection. Notice though that this only works reliably when all the methods have the same parameter type and are being passed the same argument. This is because the Type.Getmethods() method doesn't guarantee the order in which the methods are returned. However, you could get around this by sorting the method names first:
using System;
using System.Reflection;
class Program
{
static void Main()
{
MyClass mc = new MyClass();
int[] args = new int[]{1,2,3};
Type t = typeof(MyClass);
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic
|BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo[] mia = t.GetMethods(bf);
foreach(int arg in args)
{
object[] oa = new object[]{arg};
foreach(MethodInfo mi in mia)
{
if(!mi.IsConstructor)
mi.Invoke(mc, oa);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
class MyClass
{
public void MyPublicMethod(int i)
{
Console.WriteLine("MyPublicMethod called with an argument of '{0}'", i);
}
private void MyPrivateMethod(int i)
{
Console.WriteLine("MyPrivateMethod called with an argument of '{0}'", i);
}
internal static void MyStaticMethod(int i)
{
Console.WriteLine("MyStaticMethod called with an argument of '{0}'", i);
}
}