3.9. Static VariablesΒΆ

You may define static variables (variables defined inside the class, but outside of any function definition). These variables are visible inside all of your functions. Instead of local scope, static variables have class scope. It is good programming practice generally to avoid defining static variables and instead to put your variables inside functions and explicitly pass them as parameters where needed. One common exception will arise when we get to defining objects. For now a good reason for static variables is constants: A constant is a name that you give a fixed data value to. You can then use the name of the fixed data value in expressions anywhere in the class. A simple example program is constant.cs:

using System;

class Constant
{
   static double PI = 3.14159265358979; // constant, value not reset

   static double circleArea(double radius)
   {
      return PI*radius*radius;
   }

   static double circumference(double radius)
   {
      return 2*PI*radius;
   }

   static void Main()
   {
      Console.WriteLine("circle area with radius 5: " + circleArea(5));
      Console.WriteLine("circumference with radius 5:" + circumference(5));
   }
}

See that PI is used in two functions without being declared locally.

By convention, names for constants are all capital letters.

Previous topic

3.8. Local Scope

Next topic

3.10. Not using Return Values

This Page