Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic foreach loop in C#

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;
    }
}
like image 713
mcoolbeth Avatar asked Dec 17 '22 01:12

mcoolbeth


1 Answers

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;
    }
}
like image 68
Lucero Avatar answered Dec 30 '22 06:12

Lucero