Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload the Constructor of the generic class, Based on Type

I am trying to overload a constructor besides default constructor, which will get called for only type int. The closest thing I got is this.

If it is not possible, why is that?

class Program
{
    static void Main()
    {
        //default construcotr get called
        var OGenerics_string = new Generics<string>();

        //how to make a different construcotr for type int
        var OGenerics_int = new Generics<int>();
    }

    class Generics<T>
    {
        public Generics()
        {
        }
        // create a constructor which will get called only for int
    }
}
like image 480
user8260166 Avatar asked Dec 06 '25 03:12

user8260166


1 Answers

It's not possible to overload the constructor (or any method) based on the generic type - but you could create a factory method:

class Generics<T>
{
    public Generics()
    {
    }

    public static Generics<int> CreateIntVersion()
    {
          /// create a Generics<int> here
    }
}

Short of that, you'd have to check the generic type in the shared constructor using reflection and branch the code, which would be fairly ugly.

like image 50
D Stanley Avatar answered Dec 07 '25 15:12

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!