Mega Code Archive

 
Categories / C# Tutorial / Class
 

Use static

There are several restrictions that apply to static methods: A static method does not have a this reference. A static method can directly call only other static methods. A static method cannot directly call an instance method of its class. A static method must directly access only static data. You can't directly access a non-static variable from within a static method. You can't directly call a non-static method from within a static method. using System;    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());    }  } Initial value of StaticDemo.val is 100 StaticDemo.val is 8 StaticDemo.valDiv2(): 4