I have a generic class in C# with 2 constructors:
public Houses(params T[] InitialiseElements)
{}
public Houses(int Num, T DefaultValue)
{}
Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).
E.g. Houses<int> houses = new Houses<int>(1,2)
- calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.
Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?
A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference:
public static class Houses
{
public static Houses<T> CreateFromElements<T>(params T[] initialElements)
{
return new Houses<T>(initialElements);
}
public Houses<T> CreateFromDefault<T>(int count, T defaultValue)
{
return new Houses<T>(count, defaultValue);
}
}
Example of calling:
Houses<string> x = Houses.CreateFromDefault(10, "hi");
Houses<int> y = Houses.CreateFromElements(20, 30, 40);
Then your generic type's constructor doesn't need the "params" bit, and there'll be no confusion.
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