Method Types


Depending on your class design pattern, some methods will perform actions on specific instances of your class and other methods will be more neutral in purpose and will perform generalized actions that are not specific to any particular instance of your class. These two types of methods are known as instance methods and static methods respectively.

Instance methods perform actions that are specific to an instance of a class. When a method is invoked on an object, it has no direct effect on any other object. Instance methods can have an indirect effect on other objects if they share common resources such as databases, and can also use a keyword called this. As you may know, the this ‘variable’ is a reference to instance of the object on which this method was invoked. this can be used to access other object instance members such as private methods and private fields.

Of course, in a user-defined value type, we can still have instance methods, and the this keyword is still available. But it's not a reference to the instance on which the method was invoked; that would make no sense in a non-reference type. When we call a method on a value type, the value itself is copied into the new stack frame, where we can access it using the name this, and then when method execution completes, the value is copied back into the location from which it came. This actually means that in an instance method in a value type, we can assign a new value to this, and it will be this value that is copied back on method termination.

Static methods are used when the purpose of the method does not apply to a specific instance of a class. Unlike instance methods, static methods cannot access this, and can also only access other static members in the class.

Instance and Static Method Example

The following example called method_types.cs illustrates the above-mentioned points. The example is based on an Account class to represent a bank account. The class supports two methods – GetAllAccounts() and DepositMoney():

    using System;    using System.Data;    public class Account    {      public static DataSet GetAllAccounts()      {        return (new DataSet());      }      public void DepositMoney(decimal amount, string accountNumber)      {        if (this.validateAccount(accountNumber))        {          // Deposit Money to the correct account        }      }      private bool validateAccount(string accountNumber)      {        return true; // Assume Account Number is ok      }    }    public class Payments    {      static void Main()      {        DataSet dsAccountList = Account.GetAllAccounts();        Account account = new Account();        account.DepositMoney((decimal)249.99, "56329SVZ");      }    } 

Here are the observations you should make in this example:

  • GetAllAccounts() is a static method. Static methods must be invoked by specifying the name of the type first followed by the method name. In this example we use Account.GetAllAccounts().

  • DepositMoney() is an instance method. Instance methods can only be accessed by creating an instance of the object account.DepositMoney(). DepositMoney invokes a private instance method called validateAccount() using the hidden this parameter this.validateAccount().

Instance and Static Method Best Practice

When designing your method types, here are guidelines to help you design better instance and static methods:

  • When designing your classes, it's best not to have lots of static methods in a class that also has many instance methods. If this situation arises, consider splitting instance and static methods into two separate classes to make your design clearer. The class with the static methods is called a group abstraction.

  • Static methods can only be invoked by specifying the type name first. This differs from C++, which allows static methods to be invoked from an object instance. This enforcement by the C# compiler should be considered a positive thing because of the nature and purpose of static methods – it makes sure that the programmer's intentions are always clear from the code.

  • Be careful of concurrency issues if a class with a static method is used in multi-threaded code. Because each thread will access the same static method and therefore access the same static fields, static data and shared resources will be volatile if accessed concurrently. This is less of an issue with instance methods, provided instances are not shared between threads.

  • If an instance method invokes other instance members, use the this keyword to make the code clearer.




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