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

Overloading Methods

C# is very type specific. You must match the input parameters exactly; including the return type, the number of parameters, and their order. So a while back ago I passed an unsigned int into our Console.Write() method. And we know that we can pass strings to the same method. This is possible by method overloading.

Method overloading allows you to create multiple methods in one class that have the same name but take different signatures. Here's an example of a method signature:

//  methodName ( parameterName)
string myMethod(int myInt, string myString)

As long as the signatures differ, you can overload them by creating methods of the same name. Accessibility is not included as part of the signature. Here's an overloaded method for you:

class Client
{
        private string name;
 
        // If no parameter is passed, sets name to a default value
        public void SetName()
        {
                name = "Anonymous";
        }
 
        // If a string parameter is passed then it will be set to the value
        // of that parameter
        public void SetName(string newName)
        {
                name = newName;
        }
}

If you tried to call the method using a parameter that's an integer, or with two parameters, you'll get something like... "No overloaded method containing...". If you have methods with similar functionality it's a good idea to overload it rather than creating a method with a unique name.

<< Previous

Next >>