Calling non-static methods from within static methods.

  • Thread starter Thread starter koredump
  • Start date Start date
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();
}
}
 
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?
 
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.
 
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.
 
Back
Top