Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a non-static class with a console application

I'm trying to call a method from another class with a console application. The class I try to call isn't static.

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        var myString = p.NonStaticMethod();
    }

    public string NonStaticMethod()
    {
        return MyNewClass.MyStringMethod(); //Cannot call non static method
    }
}

class MyNewClass
{
    public string MyStringMethod()
    {
        return "method called";
    }
}

I get the error:

Cannot access non-static method "MyStringMethod" in a static context.

This works if I move the MyStringMethod to the class program. How could I succeed in doing this? I cannot make the class static nor the method.

like image 605
Freddy Avatar asked Jun 12 '14 09:06

Freddy


People also ask

How do you call a non static class?

To call a non-static variable from a static method, an instance of the class has to be created first. In this example, the integer a is not static. So to access it from the static method main, an instance of the class Calc has to be created.

How do I call a non static method in the same class?

But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.

Can we call non static method from Main?

To call a non-static method from main in Java, you first need to create an instance of the class, post which we can call using objectName. methodName().

How do I call a non static method in C#?

We can call non-static method from static method by creating instance of class belongs to method, eg) main() method is also static method and we can call non-static method from main() method . Even private methods can be called from static methods with class instance.


1 Answers

Just like you create an instance of the Program class to call the NonStaticMethod, you must create an instance of MyNewClass:

public string NonStaticMethod()
{
    var instance = new MyNewClass();
    return instance.MyStringMethod(); //Can call non static method
}
like image 71
MarkO Avatar answered Nov 09 '22 11:11

MarkO