views:

281

answers:

3

The compiler, given the following code, tells me "Use of unassigned local variable 'x'." Any thoughts?

public delegate Y Function<X,Y>(X x);

public class Map<X,Y>
{
    private Function<X,Y> F;

    public Map(Function f)
    {
        F = f;
    }

    public Collection<Y> Over(Collection<X> xs){
        List<Y> ys = new List<Y>();
        foreach (X x in xs)
        {
            X x2 = x;//ys.Add(F(x));
        }
        return ys;
    }
}
+2  A: 

The language specification defines foreach statement as the equivalent of a while loop, in which the loop variable is assigned to the Current property of the enumerator object. This definitely satisfies the definite assignment rules of any conforming C# compiler for that code snippet. Either you're using a non-conforming compiler or the error is from somewhere else.

Mehrdad Afshari
+4  A: 

After fixing the obvious errors it compiles fine for me.

public delegate Y Function<X,Y>(X x);

public class Map<X,Y>
{
    private Function<X,Y> F;

    public Map(Function<X,Y> f)
    {
        F = f;
    }

    public ICollection<Y> Over(ICollection<X> xs){
        List<Y> ys = new List<Y>();
        foreach (X x in xs)
        {
            X x2 = x;//ys.Add(F(x));
        }
        return ys;
    }
}
Lucero
+1, you beat me to it.
Jens Granlund
+2  A: 

This: public Map(Function f)

Should be:

public Map(Function<X,Y> f)

And this:

public Collection<Y> Over(Collection<X> xs)

Should be:

public ICollection<Y> Over(ICollection<X> xs)

Or:

public List<Y> Over(Collection<X> xs)
JonH
or IEnumerable<Y> then you can toss the list and replace the `.Add(...)` with `yield return ...`
Matthew Whited