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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With