Why is this error "local variable cannot be declared in this scope because it ... is already used"?
c#, closures, delegates, lambda, recursion
Solution
static void PrintTree<T>(Tree<T> t)
{
//Traversal<T> df = (t, a)=> **************
Traversal<T> df = null;
//========================================
df = (t, a) =>
{
if (t == null) return;
a(t.Value);
df(t.Left, a);
df(t.Right, a);
};
}
That's because `Tree<T> t` is one declaration And `(t,a) =>` is another declaration.. practically the same thing as saying:
int someFunction(T t, U a)
//Assuming int is the return type
Anyway to fix: change `t` to another identifier.. `n` for example
df = (n,a) =>{
if (n == null) return;
a(n.Value);
df(n.Left, a);
df(n.Right, a);
};
}
Problem
I am trying to run the code from the blog article by Eric Lippert "Why does a recursive lambda cause a definite assignment error?" but instead of running (or giving the compilation "definite assignment error" I am getting: A local variable named 't' cannot be declared in this scope because it would give a different meaning to 't', which is already used in a 'parent or current' scope to denote something else Why? Where is it already used in parent or current scope? Tried to rename it having gotten the same error How should I change the code to launch this code? ``` using System; namespace LippertRecursiveLambdaError { class Program { static void Main(string[] args) { Tree<int> tree = new Tree<int> (3, new Tree<int> (4, new Tree<int>(1), null), new Tree<int>(5)); PrintTree(tree); Console.ReadLine(); } delegate void Action<A>(A a); delegate void Traversal<T>(Tree<T> t, Action<T> a); static void DepthFirstTraversal<T>(Tree<T> t, Action<T> a) { if (t == null) return; a(t.Value); DepthFirstTraversal(t.Left, a); DepthFirstTraversal(t.Right, a); } static void Traverse<T>(Tree<T> t, Traversal<T> f, Action<T> a) { f(t, a); } static void Print<T>(T t) { System.Console.WriteLine(t.ToString()); } /*static void PrintTree<T>(Tree<T> t) { Traverse(t, DepthFirstTraversal, Print); }*/ static void PrintTree<T>(Tree<T> t) { //Traversal<T> df = (t, a)=> ************** Traversal<T> df = null; //======================================== //The next line gives compilation error //A local variable named 't' cannot be declared in this scope //because it would give a different meaning to 't', //which is already used in a 'parent or current' scope to denote something else df = (t, a) => { if (t == null) return; a(t.Value); df(t.Left, a); df(t.Right, a); }; Traverse(t, df, Print); }//PrintTree }//class class Tree<T> { public Tree<T> Left; public Tree<T> Right; public T Value; public Tree(T value) { Value = value; } public Tree(T value, Tree<T> left, Tree<T> right) { Value = value; Left = left; Right = right; } } }//namespace ```