overloading

Method Overloading Continued

 

 

Yesterday we learned about Method Overloading, namely creating more than one method by the same name in the same class. We’ll wrap up Method Overloading today.

In the previous post, the example used was that of a Logger class with two versions of LogError() method, one taking an Exception as a parameter and the other an error message string:

public void LogError(string errorMessage)
{
   // Log the error message
}

public void LogError(Exception ex)
{
   // Log the error
}

1. Overloads Can Call Each Other 

Overloads are regular methods. Just like those, overloads can call one another. For example, we can do this:

public void LogError(Exception ex)
{
   LogError(ex.Message);
}

The overload with the exception parameter is calling the one with the string parameter. A fine approach here as long as we are happy to use only the exception message for our logging.

It’s worthwhile noting that we must be careful not to get into infinite recursion. Given that overloads possess the same name, it’s easy to call ourselves again:

public void LogError(Exception ex)
{
   LogError(ex);   // StackOverflowException!
}

LogError(Exception) is calling LogError(Exception) recursively. We will end up with the dreaded StackOverflowException. Please be careful or write unit tests!

2. Constructor Overloading

Overloading shines when it comes to object construction. Constructors are methods and can be overloaded:

Person()
Person(string firstName, string lastName)
Person(Person person)

These constructor signatures are valid. Why overload the constructors in this way? It looks like we have the initialising data for a Person object in different forms. In each case, we hand that data to a constructor overload which then knows how to initialise the new Person object. 

3. Only Parameter Types And Order

What determines whether we can overload or not? Only the parameter types and their order. The names of the parameters do not matter. Neither does the return value. Both of these constructor signatures have two string parameters:

Person(string firstName, string lastName)
Person(string nickName, string emailAddress)

The compiler sees these as identical method signatures, not valid overloads, and it will complain. 

On the other hand, the compiler will be fine with these constructor signatures:

Person(string name, int age)
Person(int age, string name)

 In both cases, the parameters are an integer and a string. However, the order is different – and that is what matters.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply