[Gtk-sharp-list] Mono compile problem with " Use of unassigned local variable"

Jonathan Pryor jonpryor at vt.edu
Sun Dec 10 10:08:22 EST 2006


On Sun, 2006-12-10 at 09:20 +0000, Peter Morgan wrote:
> The probem is with the selected row.. I'm trying to get the current
> iter, however the compiler dails to compile with the error
> glade.cs (289,38): error CS0165: Use of unassigned local variable
> `currIter'
> Compilation failed: 2 error(s), 3 warnings

The compiler's flow analysis isn't as good as ours.  (Alternatively,
it's better than ours...)

For example, the compiler doesn't know that currIter is valid when
iterFound is true; it only follows assignment for variables
individually.

So what the compiler sees is this:

	TreeIter currIter;
	// ...
	foreach(TreePath tPath in treePaths){
	    if(this.usersListStore.GetIter(out currIter, tPath)) {
		// currIter is valud here
	        Console.WriteLine("YES");
	        iterFound = true; 
	    }
	}
	// ...
	// state of currIter here?
	this.treeView.Selection.SelectIter(currIter); 
	

But if `treePaths' is empty, no loop iterations will occur, so currIter
will remain uninitialized.  The compiler knows this, assumes the worst,
and believes that currIter won't be initialized by the end of the
`foreach' block.  So the compiler is correct, in a worst-case scenario.
You've protected against this by using iterFound, but the compiler
doesn't know that.

The solution is to initialize currIter:

	TreeIter currIter = new TreeIter ();

This will let the compiler know that it was actually initialized.
You'll still need `iterFound' to know if it is set to an interesting
value (the default constructor won't be an "interesting value"), but
this will please the compiler.

 - Jon




More information about the Gtk-sharp-list mailing list