91

I have the following code, I want to call data1() from data2(). Is this possible in C#? If so, how?

private void data1()
{
}
private static void data2()
{
   data1(); //generates error
}
George Stocker
  • 57,289
  • 29
  • 176
  • 237
Yayan
  • 991
  • 1
  • 8
  • 9

11 Answers11

143

You'll need to create an instance of the class and invoke the method on it.

public class Foo
{
    public void Data1()
    {
    }

    public static void Data2()
    {
         Foo foo = new Foo();
         foo.Data1();
    }
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 3
    What if this method is within a asp page? I am currently struggling with that. One does not manually create an instance of an asp page. So how would I go about calling a method withing an asp page, from a static method? (WebMethod) – Dean Martin Aug 07 '13 at 08:02
  • 4
    @ReidGarwin it seems really wrong to put behavior in something in a page and attempt to call it from elsewhere. Perhaps it should be refactored back to another class and take a Page instance as a dependency if required. Though, honestly, this whole pattern screams there is something wrong and I would avoid it even when possible. – tvanfosson Aug 07 '13 at 13:02
  • This is a deceptive solution: It will not really work, as soon as Data1 relies on the instance data. If it doesn't why not make Data1static? – TaW Sep 16 '20 at 09:54
28

Perhaps what you are looking for is the Singleton pattern?

public class Singleton
{
    private Singleton() {}

    public void DoWork()
    { 
        // do something
    }

    // You can call this static method which calls the singleton instance method.
    public static void DoSomeWork()
    { 
        Instance.DoWork();
    }

    public static Singleton Instance
    {
        get { return instance; } 
    }

    private static Singleton instance = new Singleton();
}

You still have to create an instance of the class but you ensure there is only one instance.

AquaGeneral
  • 155
  • 1
  • 19
Kepboy
  • 3,733
  • 2
  • 30
  • 43
  • 1
    +1 exactly the same thing came to mind when I read his question – AaronLS Sep 01 '09 at 02:23
  • 4
    Singletons are essentially global data - they make your code hard to test (classes get coupled to the Singleton) and (if mutable) hard to debug. Avoid them (and often static methods too) when possible. Consider using a DI/IoC Container library instead if you need to. – TrueWill Sep 01 '09 at 03:03
25

You have to create an instance of that class within the static method and then call it.

For example like this:

public class MyClass
{
   private void data1()
   {
   }
   private static void data2()
   {
     MyClass c = new MyClass();
     c.data1();
   }
}
Jim W
  • 4,890
  • 2
  • 20
  • 26
12

You can't call a non-static method without first creating an instance of its parent class.

So from the static method, you would have to instantiate a new object...

Vehicle myCar = new Vehicle();

... and then call the non-static method.

myCar.Drive();
Brandon
  • 13,956
  • 16
  • 72
  • 114
11

You just need to provide object reference . Please provide your class name in the position.

private static void data2()
{
    <classname> c1 = new <classname>();
    c1. data1();
}
demo
  • 6,038
  • 19
  • 75
  • 149
Leo
  • 399
  • 4
  • 6
7

Apologized to post answer for very old thread but i believe my answer may help other.

With the help of delegate the same thing can be achieved.

public class MyClass
{
    private static Action NonStaticDelegate;

    public void NonStaticMethod()
    {
        Console.WriteLine("Non-Static!");
    }

    public static void CaptureDelegate()
    {
        MyClass temp = new MyClass();
        MyClass.NonStaticDelegate = new Action(temp.NonStaticMethod);
    }

    public static void RunNonStaticMethod()
    {
        if (MyClass.NonStaticDelegate != null)
        {
            // This will run the non-static method.
            //  Note that you still needed to create an instance beforehand
            MyClass.NonStaticDelegate();
        }
    }
}
Mou
  • 15,673
  • 43
  • 156
  • 275
1

You can use call method by like this : Foo.Data2()

public class Foo
{
    private static Foo _Instance;

    private Foo()
    {
    }

    public static Foo GetInstance()
    {
        if (_Instance == null)
            _Instance = new Foo();
        return _Instance;
    }

    protected void Data1()
    {
    }

    public static void Data2()
    {
        GetInstance().Data1();
    }
}
박병학
  • 21
  • 3
1
 new Foo();
 Foo.StaticMethod();

class Foo
{
    private static Foo foo;

    public Foo()
    {
        foo = this;
    }

    private void PrintHello()
    {
        Console.WriteLine("Hello");
    }

    public static void StaticMethod()
    {
        foo.PrintHello();
    }
}
Mahdieh Shavandi
  • 4,906
  • 32
  • 41
0

Please I think the response to your question could be :

public class <Classname> {
    static method() {
        (new <Classname>)->non-static();
    }

    non-static method(){ ...; }

    ~<Classname>(){...;}

};

When a data member is declared as static, only one copy of the data is maintained for all objects of the class. A static member has or handles a permanent storage.

for C++ and probably C#, when new operator is used, it allocates memory for a class object, the object constructor is called after the memory is allocated. Thus, as a static member is called preceded by it belonging classname, the same way the non-static member is called. Thus, the use of (new Classname) seems like a call of a member with predefined permanent storage like a static data member.

therefore, this method has an inconvenience: the memory allocated to call the non-static method can't be freed because the access to it is not saved; every time the static method which needs that non-static method is called, the memory is allocated with no access to be freed at the end of it process.

To resolve this inconvenience, the class must have a destructor to free memory allocated after each process. You could also use finalizers.

References

https://learn.microsoft.com/en-us/cpp/cpp/static-members-cpp?view=msvc-170

https://learn.microsoft.com/en-us/cpp/cpp/new-operator-cpp?view=msvc-170

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers


I hope these details will help you.


kh4m3l10n
  • 1
  • 2
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 01 '22 at 00:47
-1

Static method never allows a non-static method call directly.

Reason: Static method belongs to its class only, and to nay object or any instance.

So, whenever you try to access any non-static method from static method inside the same class: you will receive:

"An object reference is required for the non-static field, method or property".

Solution: Just declare a reference like:

public class <classname>
{
static method()
{
   new <classname>.non-static();
}

non-static method()
{

}


}
Angad
  • 82
  • 4
-2

Assuming that both data1() and data2() are in the same class, then another alternative is to make data1() static.

private static void data1()
{
}
private static void data2()
{
   data1();
}