Creating Static Methods


I mentioned earlier in this hour that there are two types of methods you can create. Instance methods are methods that belong to objects derived from a class. For example, the OpenPicture() method you wrote earlier is an instance member; it's a method that belongs to an instance of a class; in this case, the form that is derived from the form class. This is why you had to use this. in order call the memberas in this.OpenPicture();. In addition to instance members, you can also create static methods. Static methods are methods that belong to the class as a whole, not to any given object derived from the class. A good use of static methods are basic utility methods that really don't apply to a specific object. For example, say you created a method that performs a complicated mathematical function. If you had a number of different math functions, you might create a clsMath.cs class and put all of the methods in that class. But, this would require that you have to create an object based on the class before you could call the method. As I've mentioned before, creating objects takes resources and time. A better solution might be to create a general class and call it something like clsUtility.cs. Then, create the method as a static method. To create a static method, you use the static keyword after the scope designator like this:

public static int ComputeLength(string strText) {    return strText.Length; }


With instance members, you have to have an object in order to call the member. For example, if the previous method declaration didn't use the keyword static, you'd have to first instantiate an object from the class and then call the method using code similar to this (the mechanics of this is discussed in Hour 16):

clsUtility objUtility = new clsUtility(); int intResult; intResult = objUtility.ComputeLength("Sams Publishing");


If you declare the method as a static member, there is no need to instantiate an objectyou can just call the method by prefacing it with the class name, like this:

int intResult; intResult = clsUtility.ComputeLength("Sams Publishing");


Static members are a great way to expose generic functions that don't require an object instance of a class, and you will create them often.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

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