can I do this from c#:
public static void example()
{
nonstatic();
}
public void nonstatic()
{ }
if there any work around to this problem please be free to provide it and thank you
can I do this from c#:
public static void example()
{
nonstatic();
}
public void nonstatic()
{ }
if there any work around to this problem please be free to provide it and thank you
static
members of a class can be called before an instance of that class exists.
Instance members of a class can only be called after an instance of that class exists, and can only be called FROM the instance itself.
A quick work around is just to create a new object of the type you're trying to call:
new SomeClass().nonstatic();
But WHY are you doing that? Is it to make it run? Then you're not writing good code. You're just giving in. Try to push for more elegant solution.. or:
Alternatively, you can ask yourself why your method is static. Does it need to be? Would it hurt to make it non-static or make the other method static
? You can avoid these situations with some careful class design.
Edit for completeness
It might be worth calling this static
method via an instance of that object, rather than directly from the static method. That way, you don't need to pointlessly create new objects. This is because an instance of a class has access to all of the instance methods, and all of the static methods.
All You need to do is to create an instance of the class and invoke the method on it.
public class Someclass
{
public void Data1()
{
}
public static void Data2()
{
Someclass foo = new Someclass();
Someclass.Data1();
}
}
Try using Singleton pattern and then call your method on instance of Your object
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
and then
Singleton.Instance.MyNonstaticMethod()
Yes you can do it.
class Example
{
public static void example()
{
new Example().nonstatic();
}
public void nonstatic()
{
}
static void main(string[] args)
{
example();
}
}
Based on your example you be better off with this code,
public static void example()
{
static();
}
public static void static()
{
}
Now, if there was some reason that you needed a non-static member, i.e. some state, you could implement two members.
public static void static(SomeState someState)
{
// Do something thread safe with someState.
}
public void nonstatic()
{
static(this.someState);
}