What is static methods and how to use static methods in C#

Description

A static method can directly call only other static methods, but not an instance method of its class. A static method does not have a this reference.

Example

Example for static method


using System; /*www.j a  va2s .  co  m*/
 
class StaticDemo { 
  // a static variable 
  public static int val = 100;  
 
  // a static method 
  public static int valDiv2() { 
    return val/2; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
 
    Console.WriteLine("Initial value of StaticDemo.val is " 
                      + StaticDemo.val); 
 
    StaticDemo.val = 8; 
    Console.WriteLine("StaticDemo.val is " + StaticDemo.val); 
    Console.WriteLine("StaticDemo.valDiv2(): " + 
                       StaticDemo.valDiv2()); 
  } 
}

The code above generates the following result.

Example 2

The following code returns the value from a static variable from static function.


using System;/*from   www.j a  v a  2 s  .  co  m*/

class MyClass {
    public MyClass()
    {
        instanceCount++;
    }
    public static int GetInstanceCount()
    {
        return(instanceCount);
    }
    static int instanceCount = 0;
}

class MainClass
{
    public static void Main()
    {
        MyClass my = new MyClass();
        Console.WriteLine(MyClass.GetInstanceCount());
    }
}

The code above generates the following result.

Example 3

How to intialize value with static methods


using System;// w  ww. jav  a2s .  c o m

public class MyClass
{
   private static int InitX()
   {
      Console.WriteLine( "MyClass.InitX()" );
      return 1;
   }
   private static int InitY()
   {
      Console.WriteLine( "MyClass.InitY()" );
      return 2;
   }
   private static int InitA()
   {
      Console.WriteLine( "MyClass.InitA()" );
      return 3;
   }
   private static int InitB()
   {
      Console.WriteLine( "MyClass.InitB()" );
      return 4;
   }

   private int y = InitY();
   private int x = InitX();

   private static int a = InitA();
   private static int b = InitB();
}

public class MainClass
{
   static void Main()
   {
      MyClass a = new MyClass();
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor