Show C# Static and Instance methods call with simple program

Answer:In C#, Static method is called using class name and instance method (non – static) must be called using a class object in a C# program.

Static method is also known as class method and is not a part of an object of a class. All instance method, also called as non-static methods are part of an object and must be called by an object of a class in C#.

In below class Car, run () method is static and is being called by class name and engine () method is non-static method that is being called by using an object.

class Car
{
    //Static method or class method
    public static void run()
    {
        Console.WriteLine("I'm Static method");
    }
    
    //non static method or instanse method
    public void engine()
    {
        Console.WriteLine("I'm non-static/instance method!!!");
    }   

}


class Program
{
    static void Main(string[] args)
    {
        //Call static method by class name 
        Car.run();


        //Call non-static method. call method by object
        Car c = new Car();
        c.engine();
    }
}

NOTES: If you call static method using an object the compiler will complain.

As a good programming practice, if all methods of a class can be called by using class name only, solve our purpose and object is not required, it is better to have static function to avoid memory uses and unnecessary overhead of object creation. Also, make the constructor private of the class, so no one can create object.

c# code example:

class Car
{
    //Static method or class method
    public static void run()
    {
        Console.WriteLine("I'm Static method");
    }

}


class Program
{
    static void Main(string[] args)
    {
        //Call static method by class name 
        Car.run();//OK

        //Error :  cannot create object due to
        //private constructor
        Car c = new Car();
        
    }
}

NOTE: This concept can also be explained for the interview question static method vs non-static method in C# programming.

Related Posts