I stumbled upon a behaviour that I would not expect and can't find the documentation of. I have a function with 2 parameters, one of them has a default value. When the function is called inside of a Select, it for some reason takes the value it is called on and applies it for both parameters. Example:
Have the function:
private static Directions PrintDir(Directions dir, int distance = 1)
{
Console.WriteLine($"Direction {dir}, distance {distance}");
return dir;
}
If called on its own, it behaves as expected:
using System;
using System.Linq;
public class Program
{
enum Directions { Left, Up, Right, Down };
public static void Main()
{
PrintDir(Directions.Left);
PrintDir(Directions.Up);
PrintDir(Directions.Right);
PrintDir(Directions.Down);
}
}
prints:
Direction Left, distance 1
Direction Up, distance 1
Direction Right, distance 1
Direction Down, distance 1
however when called inside of LINQ expression:
using System;
using System.Linq;
public class Program
{
enum Directions { Left, Up, Right, Down };
public static void Main()
{
var dirs = Enum.GetValues(typeof(Directions))
.Cast<Directions>()
.Select(PrintDir)
.ToList();
}
}
I get:
Direction Left, distance 0
Direction Up, distance 1
Direction Right, distance 2
Direction Down, distance 3
So it appears the Directions value has been applied correctly as the dir parameter, but also converted to int and applied instead of the default value as the second distance parameter.
Why does this happen? What are the rules for functions inside Select?