locked
Chaining constructors RRS feed

  • Question

  • I want to do something like: 

    Code Snippet

    public class Sample

    {

    List<ISomeInterface> _list;

    int _someValue;

    public Sample(List<ISomeInterface> list, int someValue)

    {

    _list = list;

    _someValue = someValue;

    }

    public Sample(int someValue)

    {

    List<ISomeInterface> list = new List<ISomeInterface>();

    list.Add(new MyConcreteClass(1));

    list.Add(new MyConcreteClass(2));

    this(list, someValue); // illegal syntax

    }

    }

     

    So in a constructor with less parameters I want to create a list, add members to the list and then call the general constructor with all the parameters. I remember the above syntax is legal in Java, but what is the C# equivalent of this?

    Tuesday, June 12, 2007 2:47 PM

Answers

  • You can just use a static helper method:

     

    Code Snippet

    public class Sample

    {

    List<ISomeInterface> _list;

    int _someValue;

     

    private static List<ISomeInterface> BuildList()

    {

    List<ISomeInterface> list = new List<ISomeInterface>();

    list.Add(new MyConcreteClass(1));

    list.Add(new MyConcreteClass(2));

    return list;

    }

    public Sample(List<ISomeInterface> list, int someValue)

    {

    _list = list;

    _someValue = someValue;

    }

    public Sample(int someValue)

    : this(BuildList(), someValue)

    {

    }

    }

    Wednesday, June 13, 2007 6:28 AM

All replies

  • To chain constructors the constructor call needs to be in the initalizer list:

    Code Snippet

    public Sample(int someValue)

     : this(new List<ISomeInterface>(), someValue)

    {

    //...

    }

     


    Tuesday, June 12, 2007 2:59 PM
    Moderator
  • You can just use a static helper method:

     

    Code Snippet

    public class Sample

    {

    List<ISomeInterface> _list;

    int _someValue;

     

    private static List<ISomeInterface> BuildList()

    {

    List<ISomeInterface> list = new List<ISomeInterface>();

    list.Add(new MyConcreteClass(1));

    list.Add(new MyConcreteClass(2));

    return list;

    }

    public Sample(List<ISomeInterface> list, int someValue)

    {

    _list = list;

    _someValue = someValue;

    }

    public Sample(int someValue)

    : this(BuildList(), someValue)

    {

    }

    }

    Wednesday, June 13, 2007 6:28 AM
  • Yes, it seems the only way is using a helper method. Thank you.
    Wednesday, June 13, 2007 7:04 AM