Learning C# Part 4: Classes and Objects

Written By: Kevin Jordan

- 14 Oct 2006 -

Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 4 include: classes and objects, accessibility and scope, methods, constructors, static class members, namespaces, and XML commenting.

  1. Classes and Objects
  2. The Stack and the Heap
  3. Defining a Class and Creating an Object
  4. Defining Accessibility and Scope
  5. Passing Parameters to a Method
  6. Overloading Methods
  7. Using Constructors
  8. Static Class Members
  9. Namespaces and XML Commenting
  10. Aww Man... Not Homework

Static Class Members

Returning back to our good old Console.Write... Did you notice that we didn't have to create an Console object before using it? If you did, awesome, if not, that's cool too. Either way, pay attention, because static class members are very useful. Whenever you want to create a method, but it just doesn't make since to have an object associated with it, use a static method. Think about all the math functions. Why should you have to create a Math object when you want to find the square of a number? Anyway, here's how you use it.

// I know a much better math class already exists, this is just an example
class SimpleMath
{
        public static double pi = 3.14159; // etc.
        
        public static double DoubleIt(double dblValue)
        {
                return dblValue * 2;
        }
}
 
// Let's use the static members
class WinForm
{
        static void Main()
        {
                Console.Write("Pi = " + SimpleMath.pi.ToString());    // Outputs Pi = 3.14159
                double morePi = SimpleMath.DoubleIt(SimpleMath.pi);
                Console.Write("Yummy pi = " + morePi.ToString());  // Outputs Yummy pi = 6.28318
        }
}

Not too shabby. Static members are accessed through the class. That's why we have to include the class name in front of the static member. If you're like me though, you'd rather avoid typing whenever possible, so let's jump into namespaces.

<< Previous

Next >>