General foreach loop in C #

The compiler, given the following code, tells me: "Using the 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; } } 
+4
source share
3 answers

After fixing obvious errors, it compiles 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; } } 
+6
source

The language specification defines the foreach as the equivalent of the while , in which the loop variable is assigned to the Current property of the enumerator object. This definitely satisfies the specific assignment rules of any suitable C # compiler for this piece of code. Either you use an inappropriate compiler, or the error occurs somewhere else.

+2
source

This is: public Map(Function f)

Must be:

 public Map(Function<X,Y> f) 

And this:

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

Must be:

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

Or:

 public List<Y> Over(Collection<X> xs) 
+2
source

Source: https://habr.com/ru/post/1305588/


All Articles