Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor chaining

Tags:

c#

.net

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 ?

like image 693
Moe Sisko Avatar asked Jan 22 '23 17:01

Moe Sisko


2 Answers

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).

like image 68
Rex M Avatar answered Jan 27 '23 13:01

Rex M


I would ditch the ListHelper in favor of the following:

public CA(string s, int num) : this(s, new List<int>(){num}){}
like image 28
Josh Bush Avatar answered Jan 27 '23 12:01

Josh Bush