How To Call Non-Static Method From Static Method

Introduction

In this blog, we discuss static keyword, static method, and how to call a non-Static method from the Static method.

Static is a keyword. As the word implies,  it keeps a static value and holds it till the end of the program. The static keyword is used after access specifier and before data type.

Example

public static int i = 2;

We can use 'i' value throughout the program. Static is like constant but for static memory is allocated and values assigned at run time.

We can create a static method inside the non-static class.

class Program {
    public static void Main(string[] args) {
        TestMethod();
        staticFunction();
    }
    public void TestMethod() {
        Console.WriteLine("Inside non-static function");
    }
    public static void staticFunction() {
        Console.WriteLine("Inside static function");
    }
}

In the above code we created method staticFunction() inside non-static class "Program". 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.

staticFunction() method is a static method, we can call this method directly.

class Program {
    public static void Main(string[] args) {
        Program p = new Program();
        p.TestMethod();
        staticFunction();
    }
    public void TestMethod() {
        Console.WriteLine("Inside non-static function");
    }
    public static void staticFunction() {
        Console.WriteLine("Inside static function");
    }
}

Summary

In this blog, we discussed how to implement and invoke static and non-static methods from the class with code samples. I hope it is helpful for beginners.


Next Recommended Reading How to use this keyword in static method