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.
this
or any other 'attributes' belonging to an instance context. – KermitkermyConsole.WriteLine("Test2");
from theMain
method? All of this just to show a simple message. If you want to learn about reflection, try not to use a static context to do this. – Fiendish