tags:

views:

139

answers:

3

Sample code :

public class CA
{
    public CA(string s, List<int> numList)
    {
        // do some initialization
    }

    public CA(string s, int num) : this(s, ListHelper.CreateList(num))
    {
    }
}

public static class ListHelper
{
    public static List<int> CreateList(int num)
    {
        List<int> numList = new List<int>();
        numList.Add(num);
        return numList;
    }
}

The second constructor in "CA" uses constructor chaining. Inside the "this" call, I want to convert an int into a List with one member. The code works via the helper function "CreateList", but I'm wondering if there is a cleaner way than this. i.e. is there some way to do it without the helper method.

To date, in situations like this, I probably wouldn't bother using constructor chaining. Thoughts ?

+4  A: 

Try:

public CA(string s, int num) : this(s, new List<int>(new int[] { num }))
{
}

This should match the constructor overload which takes an IEnumerable<T> (which an array of T[] is convertible to).

Rex M
+2  A: 

I would ditch the ListHelper in favor of the following:

public CA(string s, int num) : this(s, new List<int>(){num}){}
Josh Bush
the compiler doesn't seem to like this ? (gives syntax errors - at least in VS2005)
Moe Sisko
Yeah, the construct used here is new in C# 3.0. See http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic14
ephemient
@ephemient - thanks for clearing that up
Moe Sisko
A: 

I have a little something in my extensions for when I don't have an enumerable of something to initiate a list, that should do the trick.

namespace Linq1
{
    class Program
    {
        static void Main(string[] args)
        {
            int value = 10;
            List<int> list = value.ToList();
        }
    }

    public static class Extensions
    {
        public static List<T> ToList<T>(this T lonely) where T : struct
        {
            return new List<T>(new T[] { lonely });
        }
    }
}

and used in your code:

public class CA
{
    public CA(string s, List<int> numList)
    {
        // do some initialization
    }

    public CA(string s, int num) : this(s, num.ToList())
    {
    }
}
Dynami Le Savard
Extension methods also are new in C# 3.0: http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic3
ephemient