Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# params keyword in a constructor of generic types

Tags:

c#

.net

c#-3.0

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?

like image 388
sixtowns Avatar asked Oct 17 '08 18:10

sixtowns


1 Answers

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.

like image 158
Jon Skeet Avatar answered Sep 20 '22 05:09

Jon Skeet