Call function from Main()

Arbitur picture Arbitur · Apr 10, 2014 · Viewed 30.5k times · Source

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.

Answer

DmitryBoyko picture DmitryBoyko · Apr 10, 2014

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();
        }