Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, is there a way to write custom object initializers for new data-types?

In C#, there's the "standard" initializer technique { Property1 = "a", Property2 = "b" }, and there are a couple of special variants for collections (list and dictionary). {value1, value2}, and { {"key1", value1 }, {"key2", value2} }.

I'd like to have a recursive object initializer for a tree data type, but I don't know if there's any way to customize that mechanism. I'd like something that looks like an s-expression. { item1 {item2 item3 item4 } {item5 item6} }

I'm doing this via constructors, but I'd like a terser syntax.

like image 556
darthtrevino Avatar asked Nov 16 '09 21:11

darthtrevino


2 Answers

If you implement the ICollection IEnumerable interface and have a method called add. Incidentally, this is all included in the ICollection interface which is why I confused it.

Test test = new Test() {
    new Test2() {
        new Test3() {

        }
    },
    new Test() {
        new Test2() {
            { new Test(), new Test2() },
            { new Test(), new Test2() },
            { new Test(), new Test2() }
        }
    }
};

public class Test : IEnumerable
{
    public void Add(Test a){}
    public void Add(Test2 a){}
    public IEnumerator GetEnumerator(){}
}

public class Test2 : IEnumerable
{
    public void Add(Test a, Test2 b){}
    public void Add(Test3 a){}
    public IEnumerator GetEnumerator(){}
}

public class Test3 : IEnumerable
{
    public void Add(Test a) {}
    public void Add(Test2 a){}
    public IEnumerator GetEnumerator(){}
}
like image 142
ChaosPandion Avatar answered Sep 19 '22 13:09

ChaosPandion


Using a variadic local lambda n that simply calls your constructor, you could get it as short as:

n(item1, n(item2, item3, item4), n(item5, item6))

Update: something like

var n = (params Node[] nodes) => new Node(nodes);
like image 31
Thomas Avatar answered Sep 22 '22 13:09

Thomas