[ACCEPTED]-Using C# params keyword in a constructor of generic types-c#-3.0

Accepted answer
Score: 15

A clearer solution would be to have two 6 static factory methods. If you put these 5 into a nongeneric class, you can also benefit 4 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 3 your generic type's constructor doesn't 2 need the "params" bit, and there'll be no 1 confusion.

Score: 2

Perhaps instead of Params you could pass 1 in IEnumerable

public Houses(IEnumerable<T> InitialiseElements){}
Score: 2

The 2nd constructor is a more exact match, which 2 is the criteria used to evaluate which constructor 1 is correct.

Score: 2

Given the following since the original did 6 not have too much information on the class 5 etc.

The compiler is going to decide new 4 House(1,2) matches the second constructor 3 exactly and use that, notice that I took 2 the answer with the most up votes and it 1 did not work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericTest
{
    public class House<T>
    {
        public House(params T[] values)
        {
            System.Console.WriteLine("Params T[]");
        }
        public House(int num, T defaultVal)
        {
            System.Console.WriteLine("int, T");
        }

        public static House<T> CreateFromDefault<T>(int count, T defaultVal)
        {
            return new House<T>(count, defaultVal);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            House<int> test = new House<int>(1, 2);                         // prints int, t
            House<int> test1 = new House<int>(new int[] {1, 2});            // prints parms
            House<string> test2 = new House<string>(1, "string");           // print int, t
            House<string> test3 = new House<string>("string", "string");    // print parms
            House<int> test4 = House<int>.CreateFromDefault<int>(1, 2);     // print int, t
        }
    }
}

More Related questions