I am new to C# and I'm having a little problem with calling a function from the Main() method.
class Program
{
    static void Main(string[] args)
    {
        test();
    }
    public void test()
    {
        MethodInfo mi = this.GetType().GetMethod("test2");
        mi.Invoke(this, null);
    }
    public void test2()
    { 
        Console.WriteLine("Test2");
    }
}
I get a compiler error in test();:
An object reference is required for the non-static field.
I don't quite understand these modifiers yet so what am I doing wrong?
What I really want to do is have the test() code inside Main() but it gives me an error when I do that.
If you still want to have test() as an instance method:
class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.test();
    }
    void Test()
    {
        // I'm NOT static
        // I belong to an instance of the 'Program' class
        // You must have an instance to call me
    }
}
or rather make it static:
class Program
{
    static void Main(string[] args)
    {
        Test();
    }
    static void Test()
    {
        // I'm static
        // You can call me from another static method
    }
}
To get the info of a static method:
typeof(Program).GetMethod("Test", BindingFlags.Static);
                        Just put all logic to another class
 class Class1
    {
        public void test()
        {
            MethodInfo mi = this.GetType().GetMethod("test2");
            mi.Invoke(this, null);
        }
        public void test2()
        {
            Console.Out.WriteLine("Test2");
        }
    }
and
  static void Main(string[] args)
        {
            var class1 = new Class1();
            class1.test();
        }
                        The method must be static in order to call it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With