static versus private.
Suppose you have a class named clsPerson with a private member named Age. if you write code that creates 100 clsPerson objects, you will get 100 private members named Age.
Now suppose that class has a variable defined as:
static String days[]={"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
Because you used the keyword static the compiler does two important things:
1) Immediately at program start, it creates the days[] array, even if you have not defined a clsPerson yet.
2) It will never create another days[] array regardless of how many other new clsPerson objects you define.
This means that every clsPerson object shares the same days[] array...it is never reassigned. Therefore, anytime you have data that likely won't change during program execution, making it a static can save code space by not duplicating the data. It should also be obvious that static data within methods retains its values between calls to the method.
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|