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
Class Organization Through Namespaces
Namespaces are used to organize classes into a logically related hierarchy. They also help to avoid name clashes (naming a class something that already exists).
Let's say that I didn't want my math class called SimpleMath, I wanted it called Math. Well, Math already exists as part of the .NET Framework Class Library. So how would I differentiate my Math from their Math.
namespace ScratchProjects { class Math { public static double pi = 3.14159; // etc. // Other math stuff } }
Now we can use my Math class like this:
double myDouble = ScratchProjects.Math.pi;
So simple, but so much typing. What we can do is put a using directive at the top of our code. The using directive is a shortcut that tells your application that the types in the namespaces can be referenced without using the fully qualified name. Check it out.
using ScratchProjects.Math; // now we can use it just by calling pi double myDouble = pi;
The example may not seem to help that much, but if you really love pi, then that'll save ya.
XML Code Comments
One major feature of Visual Studio .NET is the use of IntelliSense. When you're starting out a method, you'll notice a little popup box that tells you what variables are accepted and a little description of the method and those variables. XML commenting is how you get those little descriptions on your methods.
////// Doubles the value /// /// Number to be doubled /// A number thats double the original value public static double DoubleIt(double dblValue) { return dblValue * 2; }
Now this may seem like a lot of typing, and we know I hate typing, but just type three slashes (///) and most of it will show up automatically for you. This is one of the most neglected features of Visual Studio, but I highly suggest you use them. It only takes an extra minute or two and everyone will love you for it.