Search code examples
c#genericsoverloadingoverload-resolutionconstructor-overloading

Overload-resolution in generic constructors


I created a mockup class to ilustrate the question:

 public class Anything<T>
    {
        /// <summary>
        /// Generic typed constructor
        /// </summary>
        /// <param name="param1"></param>
        public Anything(T param1)
        {
            Console.WriteLine("I'm generic typed constructor");
        }

        /// <summary>
        /// String typed constructor
        /// </summary>
        /// <param name="param1"></param>
        public Anything(string param1)
        {
            Console.WriteLine("I'm string typed constructor");
        }
    }

Whats up if I build Anything of string object? There is no way to differentiate both constructors. It's a bad practice define another constructor with the same number of parameters?

Two constructos looks equal


Solution

  • The compiler will always choose the most specific overloaded method, that is the one with the stringparameter in its signature. Even if you have a generic method (or constructor in your case) the explicitly typed string parameter is the most specific one. Thus

    new Anything<string>("test");
    

    will output

    I'm string typed constructor


    From a software engineering perspective, it is indeed a bad practice because it would not be clear to the user of the class why for example the constructor with the string parameter would exhibit different behavoir than the generic one.