Web Design that taps into the haromny and vision of your dreams.

Method Overloading and Overriding in C#

Overloading methods

Written By on in C#

794 words, estimated reading time 4 minutes.

When inheriting from another class, you may wish to change the default behaviour of a method or create a different method signature. You can do this by overloading the method with your own code.

Advanced C# Programming Series
  1. C# Advanced Data Types
  2. Using C# Properties and Indexers
  3. C# Event Handling and Delegates
  4. Method Overloading and Overriding in C#
  5. C# Class Abstraction and Encapsulation
  6. C# Aggregation and Advanced Scope Techniques
  7. Polymorphism in C#
  8. Boxing and Unboxing Value Types in C#
  9. C# Operator Overloading
  10. Creating Multi-Threading Applications with C#
  11. Unsafe Code Execution in Microsoft .Net

Method signatures are formed from the parameter list, in particular, the data types. Methods can share the same name within the class as long as the signature is different.

static int Add(int a, int b)
{
  return a + b;
}

In the above example, the signature should be (int, int). In the Visual Studio code editor, if you were to call the Add method after you enter the '(' IntelliSense will pop-up the available parameters. Notice that there is only one option given to you.

Method Overloading

We can add an overloaded method with a different signature and IntelliSense will now present two options, one for each signature of the overloaded method. The compiler finds two methods of the same name and two calls to that method with different parameters. It is able to tell the difference by comparing the signatures of the methods.

static int Add(int a, int b, int c)
{
  return a + b + c;
}

The names of the parameter and the return type have no effect on the method signature, thus the method below will raise an error because a method already exists for Add(int, int), even though it returns a decimal.

static decimal Add(int a, int b, int c)
{
  return a + b + c;
}

Methods should be overloaded when you have similar methods that require differing parameters or you want to add new functionality to existing code, however, you should not use overloading to often as it causes headaches during debugging and testing and is more effort to maintain.

Optional Parameters in C#

C# does not have an implementation of optional parameters like those found in PHP, however, you can simulate this feature using method overloading.

static int Add(int a, int b)
{
  return Add(a, b, 0, 0);
}
 
static int Add(int a, int b, int c)
{
  return Add(a, b, c, 0);
}
 
static int Add(int a, int b, int c, int d)
{
  return (a + b + c + d);
}

In this example we can call Add with 2, 3 or 4 parameters and only one functional method is called - the others just pass the data around. You can use IntelliSense to see the different overloads and their parameters.

Overloading Example
Overloading Example

Full Code

using System;
using System.Drawing;
 
class TestBaseCarClass
{
    static void Main()
    {
        Console.WriteLine(Add(1, 1));
    }
 
    static int Add(int a, int b)
    {
        return Add(a, b, 0, 0);
    }
 
    static int Add(int a, int b, int c)
    {
        return Add(a, b, c, 0);
    }
 
    static int Add(int a, int b, int c, int d)
    {
        return a + b + c + d;
    }
}
 

NB. This code is only shown as an example. If you really want to create a function that accepts any number of parameters of the same type, then the params keyword is better suited.

Method Overriding

Methods can be overridden, replacing the default behaviour or extending it. In this example we will override the ToString() method for the ArrayList class so that it may return something more meaningful.

using System;
using System.Collections.Generic;
 
class Program
{
  static void Main()
  {
     ArrayList myList = new ArrayList();
 
    myList.Add("Hello");
    myList.Add("World");
    myList.Add("123456");
 
    Console.WriteLine(myList.ToString());
  }
}

You may expect the ToString to return "Hello World 123456", but it actually returns "System.Collections.ArrayList", which isn't particularly helpful.

We can override this default behaviour by creating a new class, which inherits from the ArrayList. We can then override the ToString method by using the override keyword.

class myArrayList : System.Collections.ArrayList
{
    public override string ToString()
    {
        return base.ToString();
    }
}

The base keyword is used to refer to the object. By default, the override method will return base.ToString(). You can use this base object to call the non-overwritten method. We are going to amend the code to suit our needs, and in this example, we are going to convert the array list to show the contents of the list, one item per line.

using System;
using System.Text;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        myArrayList myList = new myArrayList();
 
        myList.Add("Hello");
        myList.Add("World");
        myList.Add("123456");
 
        Console.WriteLine(myList.ToString());
    }
}
 
class myArrayList : System.Collections.ArrayList
{
    public override string ToString()
    {
        StringBuilder result = new StringBuilder();
        string[] theItems = (string[])base.ToArray(typeof(string));
 
        foreach (string item in theItems)
        {
            result.AppendLine(item);
        }
        return result.ToString();
    }
}

Now when we create an instance of our new class and call the ToString method we are given "Hello World 123456" one item per line.

In Visual Studio 2005 onwards you can get the IDE to create the code for the override for you. Create the class and public override then select the method from the list. It will then fill in the remainder of the code and default return for you.

Last updated on: Saturday 24th June 2017

 

Comments
Hari

Hari

Nice Article, and good explain... keep going and help for new learners like me.
thankQ buddy

Reply to Hari
Vinod

Vinod

Nice article............

Reply to Vinod
Venkat Reddy

Venkat Reddy

Good answer.Helped me a lot.Thank u buddy...!

Reply to Venkat Reddy

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me