Calling non-static methods from within static methods.

K

koredump

Is the following legal/recommended? (It compiles w/o error or
warnings)

class MyClass()
{
public MyClass()
{
}

private string NonStaticMethod()
{
retrun "Something";
}

private static string StaticMethod()
{
MyClass mc = new MyClass();

return mc.NonStaticMethod();
}
}
 
A

AlexS

Yes. In short.

You should consider that MyClass might need proper Dispose after use. If you
will adhere to recommended practices.

However, "retrun" shouldn't compile. You don't get any errors?
 
G

Guest

What you have looks similar to the Singleton design pattern where you have a
static method that everyone can call without having to create any objects.
This in turn returns a single existing instance of a resource that is shared
by everyone. Apart from that I don't see any other reason for you to make a
static method which instantiates the class it is in. You can read more about
the Singleton design pattern here:

http://www.dofactory.com/Patterns/PatternSingleton.aspx

Adrian.
 
B

Ben Voigt [C++ MVP]

koredump said:
Is the following legal/recommended? (It compiles w/o error or
warnings)

Certainly legal. The only thing I see that is suspicious is locally
creating an instance to use, as typically the instance(s) will be passed in
via parameter. Operator overloads are required to work in this manner.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top