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
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 ( string myMethod(int myInt, string myString)parameterName)
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.