Sobes.tech
Junior

What is the difference between a static method and an instance method?

sobes.tech AI

Answer from AI

A static method belongs to the class and is called without creating an instance of the object. An instance method belongs to an instance of the class and is called through the created object.

Main differences:

Criterion Static method Instance method
Belongs to The class An instance of the class
Call Through the class name Through the object instance
Access to data Only to static members of the class To static members and instance data of the class
Keyword static Absent (by default)
using System;

public class MyClass
{
    // Static field
    public static string StaticData = "This is static data";

    // Instance field
    public string InstanceData = "This is instance data";

    // Static method
    public static void StaticMethod()
    {
        Console.WriteLine("Static method called.");
        Console.WriteLine(StaticData); // Access to static field
        // Console.WriteLine(InstanceData); // Error: no access to instance field
    }

    // Instance method
    public void InstanceMethod()
    {
        Console.WriteLine("Instance method called.");
        Console.WriteLine(StaticData); // Access to static field
        Console.WriteLine(InstanceData); // Access to instance field
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // Call static method through class name
        MyClass.StaticMethod();

        // Create an instance of the class
        MyClass myObject = new MyClass();

        // Call instance method through object
        myObject.InstanceMethod();
    }
}