Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to overload a constructor/method?

Tags:

c#

overloading

Overloading constructors and methods seems messy, i.e. simply differentiating them by the order and number of parameters. Isn't there a way, perhaps with generics, to do this cleanly so that, even if you just have one parameter (e.g. string idCode / string status) you could still differentiate them?

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TheForm tf1 = new TheForm("online", DateTime.Now);
            TheForm tf2 = new TheForm(DateTime.Now, "form1");
        }
    }

    public class TheForm
    {
        public TheForm(string status, DateTime startTime)
        {
           //...
        }

        public TheForm(DateTime startTime, string idCode)
        {
           //...
        }
    }
}
like image 684
Edward Tanguay Avatar asked Feb 02 '10 09:02

Edward Tanguay


People also ask

In what ways a constructor can be overloaded?

Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.

What are the methods of overloading constructors in Java?

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

When using overloaded constructors What must we ensure?

Constructor overloading in Java refers to the use of more than one constructor in an instance class. However, each overloaded constructor must have different signatures.


1 Answers

If you need that many overloads, perhaps your types are handling too much (see Single Responsibility Principle). Personally I rarely need more than one or a few constructors.

like image 64
Brian Rasmussen Avatar answered Nov 15 '22 07:11

Brian Rasmussen