Article
Object Oriented C# for ASP.NET Developers
Static Members
All class members (including methods, fields and properties) can be declared static. Static members belong to the class instead of to objects of that class. Since static members aren't that common in basic ASP.NET development, I won't dwell on static members too heavily; but for the sake of completeness, let's look at a simple example.
It might be useful to know the total number of trees that had been created in our program. To this end, we could create a static field called totalTrees in the Tree class, and modify the constructor to increase its value by one every time a Tree was created. Then, using a static property called TotalTrees, for which we would only define a get accessor (making it a read-only property), we could check the value at any time by checking the value of Tree.TotalTrees.
Here's the code for the modified Tree class:
public class Tree {
private static int totalTrees = 0;
private int height;
public Tree() {
this(0);
}
public Tree(int height) {
if (height < 0) this.height = 0;
else this.height = height;
totalTrees = totalTrees + 1;
}
public static int TotalTrees {
get {
return totalTrees;
}
}
// ... rest of the code here ...
}
Static members are useful in two main situations:
- When you want to keep track of some information shared by all members of a class (as above).
- When it doesn't make sense to have more than one instance of a property or method.
As I said, static members don't tend to crop up in basic ASP.NET applications, but it's useful to know about them so you're not totally bamboozled if you see someone accessing a method in a class instead of an object!