Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create hierarchical anonymous type

Is there any way to create anonymous type that references instances of itself?

var root = new { Name = "Root", Parent = ??? };
var child = new { Name = "Child", Parent = root };
var childOfChild = new { Name = "Grand child", Parent = child };

For example, we can reference delegate from itself:

Action run = null;
run = () => run();

Another example, we can create generic Stack of anonymous types:

static Stack<T> CreateStack<T>(params T[] values)
{
    var stack = new Stack<T>();

    foreach (var value in values)
        stack.Add(value);

    return stack;
}

Can you think of any ways to reference anonymous type from itself?

like image 931
Konstantin Spirin Avatar asked Mar 23 '26 10:03

Konstantin Spirin


1 Answers

Anonymous types in C# are immutable. Therefore all of their field values must have been present before the creation of the object and will never change. And therefore it is impossible to have a directly circular referencing anonymous type in C#.

Anonymous types in VB are mutable; you could probably figure out some way to do it in VB.

There might be a way to make an anonymous type indirectly reference itself, by, say, containing a delegate that when invoked, returns the instance of the anonymous type. I don't see any way off the top of my head to easily do that, but I also don't see a proof that doing so is impossible. Give it some thought and see what you come up with!

I assume this question is for entertainment purposes only. If you want to make a circularly-referential object, please make a nominal type.

like image 106
Eric Lippert Avatar answered Mar 26 '26 01:03

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!