Thursday, July 12, 2012

Static - Key things about using 'static'

In this post I'll pin point you the important facts that you should be aware of when using static methods, variable & classes etc.
  • If a there is a static field declared in a non static context (class) it can be accessed without creating an object (object of the class).
    class Sales
    {
       public static double salesTaxPercentage = 20;
    }
    Sales.salesTaxPercentage  = 35; // can access like this


  • You cannot access static fields from an instance of the type it belongs to.
    Sales _sales = new Sales();
    _sales.salesTaxPercentage = 35;  // Compile error.

  • If you declare a Class as static it cannot contain non static members such as fields, methods, and constructors.
static class Sales { public static void Sales1() {...} // Ok

public void Sales2() {...} // Compile Error
}

  • A non static context cannot be accessed within a static context.
 public int a = 0;
static class Sales {
a = 10; // Compile Error
}

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete