God of Source God of Source - 28 days ago 16
C# Question

Class initialization syntax in one line

I have the following class

public class ListCode : List<int>
{
public string Code { get; set; }
}


which can be initialized this way:

ListCode myList = new ListCode() { 1, 2, 3};
myList.Code = "bar";


But it can also be initialized that way:

ListCode myList = new ListCode() { Code = "bar"};
myList.AddRange(new[] { 1, 2, 3 });


Is there also a way to do this in one line? Like

ListCode myList = new ListCode() { 1, 2, 3, Code = "bar" }; //invalid syntax

Answer

It seems not possible to do according to the reference in comments, but I can suggest to use constructor argument for this:

public class ListCode : List<int>
{
    public ListCode(string code)
    {
        Code = code;
    }

    public string Code { get; set; }
}

ListCode myList = new ListCode("bar") { 1, 2, 3};

That seems like the cleanest you can get :)