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 ?
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).
I would ditch the ListHelper in favor of the following:
public CA(string s, int num) : this(s, new List<int>(){num}){}
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