Wednesday, June 27, 2012

C# Static Methods


Static methods have no instances. They are called with the type name, not an instance identifier i.e we have no need to create the instance of class to call the static methods.So they are slightly faster than instance methods.
The static methods use the static keyword somewhere in the method declaration signature, usually as the first keyword or the second keyword after public

Static methods cannot access non-static class level members and do not have a 'this' pointer. Instance methods can access those members, but must be called through an object instantiation, which causes another step and level of indirection.

Example : 

using System;

class MyClass
{
    static void M1()
    {
       Console.WriteLine("Static method");
    }

    void M2()
    {
        Console.WriteLine("Instance method");
    }

    static char M3()
    {
        Console.WriteLine("Static method");
        return 'M3';
    }

    char M4()
    {
        Console.WriteLine("Instance method");
        return 'M4';
    }

    static void Main()
    {
         // Call the two static methods on the Program type.
    MyClass.M1();
          Console.WriteLine(MyClass.M3());
 
    // Create a new Program instance and call the two instance methods.
              MyClass myobj=new MyClass();
     myobj.M2();
             Console.WriteLine(myobj.M4());
    }
}

Output
Static method
Static method
M3
Instance method
Instance method
M4

No comments:

Post a Comment

^ Scroll to Top