Overloading methods – c#

Overloading a method in a class is making a method name be able to take different parameters and return values. A good example would be if you had a method that was adding a passed value to a internal private variable, but wanted to be able to do different processes if the value is a integer /double / floating point number. To overload a method as above the code would be similar to this

public void addNumber(int intValue)
{
....
}
 
public void addNumber(double doubleValue)
{
...
}

Here is a basic overloading method, to just print out to the console a message.

using System;
 
namespace inheritance
{
 
	class firstClass
	{
		public void printClassName()
		{
			Console.WriteLine("FirstClass");
		}
 
		// overloading the method printClassName
		public void printClassName(String additionalMessage)
		{
			Console.WriteLine("FirstClass  : " + additionalMessage);
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			firstClass first = new firstClass();
			first.printClassName();
			// call the overloaded function to pass in a message to print out.
			first.printClassName("overloaded");
		}
	}
}

output would be

FirstClass
FirstClass  : overloaded

Leave a Reply

Your email address will not be published. Required fields are marked *