4

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;
    }
}
10
  • Could you post the entire error? And is this the real code? Commented Mar 30, 2010 at 18:30
  • Also, what version of .Net are you using? Commented Mar 30, 2010 at 18:30
  • After fixing the other errors in the code, I don't get that error. What does your code actually look like? Commented Mar 30, 2010 at 18:34
  • 1
    Shouldn't your constructor take an argument of type Function<X, Y> not Function? Commented Mar 30, 2010 at 18:35
  • 2
    Just wondering, but why would you ever need a class like this? Are you on an old version of .NET? Commented Mar 30, 2010 at 18:37

3 Answers 3

8

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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)

1 Comment

or IEnumerable<Y> then you can toss the list and replace the .Add(...) with yield return ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.