Static Type Members


The fields, properties, and methods we have seen so far in this chapter are accessible only with a reference to an instance of a class. However, not all functionality is best implemented tied to an instance of a class. .NET allows us to define type members that are callable directly from the class without requiring an instance of the class to be created. Fields, methods, and properties can all be declared in this fashion.

Static type members are useful if a particular action is not tied to an instance of the class, but is functionality that can be used as a standalone. For example, a Time class may define a GetCurrentTime() method that returns the current system clock time. Creating an instance of Time just to call GetCurrentTime() is not ideal since all classes would return the same value. Since this method is general to the Time class and is not specific to each instance, it is best implemented as a static member.

Static type members are commonplace with the .NET base class library. A trivial example of a static type member can be found with the System.DateTime class. System.DateTime.Now is a static function returning the system date, as seen in static_time_example.cs. Note that the DateTime class is used directly; we do not need to create an instance of DateTime to call the Now type member. The Now property within the DateTime class is declared as static:

    using System;    public class static_time_example    {      [STAThread]      static void Main(string[] args)      {        Console.WriteLine(DateTime.Now);      }    } 

Generally speaking, it is useful to think of static members as belonging to classes. Non-static, or instance members belong to objects, or instances of classes. If you'll recall, this is exactly how constants and static read-only fields perform. In fact, a constant is a special type of static field.

Remember, a field is a storage location for an object's data. A new storage location is created for each instance of an object. It is slightly different if a field is static. A static field denotes exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field.

Let's make one small change to our Account class to further explore how static fields affect our program. The following code is located in static_bankaccount.cs:

    using System;    public class Account    {      private static double balance;      public double Balance      {        get        {          return balance;        }          set        {          balance=value;        }      }    }    class AtTheBank    {      [STAThread]      static void Main(string[] args)      {        Account mySavings= new Account();        Account myChecking=new Account();        mySavings.Balance=500;        Console.WriteLine("Savings balance: " + mySavings.Balance);        Console.WriteLine("Checking balance: " + myChecking.Balance);      }    } 

The only change we've made to the Account class is in how we define the balance field:

       private static double balance; 

However, while this change is small, the corresponding effect on the program is quite noticeable. Look again at the two instances of Account, mySavings and myChecking:

    Account mySavings= new Account();    Account myChecking=new Account();    mySavings.Balance=500;    Console.WriteLine("Savings balance: " + mySavings.Balance);    Console.WriteLine("Checking balance: " + myChecking.Balance); 

If balance were an instance variable, then mySavings and myChecking would each have their own balance field. We would expect that the output of the above program would show that the mySavings instance had a balance of 500 while myChecking only had the default value of 0. However, balance is not an instance field. Rather, it is a static field. Because of this, the value of balance is shared across all instances of Account.

If a method is declared as static, then that method will perform an action on the class, not an instance of the class. A static member can only access and modify static fields. Let's modify the account one more time to show off the use of a static method. The following code is in static_bankaccount2.cs:

    using System;    public class Account    {      private static double balance;      public double Balance      {        //...omitted for brevity      }      public static void addTen()      {        balance=balance+10;      }    }    class AtTheBank    {      [STAThread]      static void Main(string[] args)      {        Account mySavings= new Account();        Account myChecking=new Account();        mySavings.Balance=500;        Account.addTen();        Console.WriteLine("Savings balance: " + mySavings.Balance);        Console.WriteLine("Checking balance: " + myChecking.Balance);      }    } 

Static methods act on the class, not the instances of the class. Static methods can access static fields, static properties, and other static methods. As such, you cannot call AddTen() through the mySavings or myChecking instances of the Account class. Rather, you must make the call directly against the Account class. However, as you can see from the output, the call does still affect the balance of every instance. This is because AddTen() adds to the static balance field. Here is the output of the above program:

    C:\Class Design\Ch 02>static_bankaccount2.exe    Savings balance: 500    Checking balance: 500    Savings balance: 510    Checking balance: 510 

Care must be taken when using static methods and fields. Only fields that truly must be shared across all instances should be marked as static. Similarly, only methods and properties that must act on static fields should be marked as static. An ideal situation to use static methods and fields is in conjunction with the read-only attribute.




C# Class Design Handbook(c) Coding Effective Classes
C# Class Design Handbook: Coding Effective Classes
ISBN: 1590592573
EAN: 2147483647
Year: N/A
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net