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?
It seemed… that the C# compiler will simply refuses to infer the type recursively. Take this sample code for example:
(From @Eric: Correct; the type inference engine requires that all the “input” types of a lambda be known before the “output” type of the lambda is inferred)
This snippet fails to compile with an error that the compiler cannot infer the
<T>to use withGenerator<T>… thus I think it’s impossible.