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.
- Classes and Objects
- The Stack and the Heap
- Defining a Class and Creating an Object
- Defining Accessibility and Scope
- Passing Parameters to a Method
- Overloading Methods
- Using Constructors
- Static Class Members
- Namespaces and XML Commenting
- 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.