I'm trying to get rid of some code with anonymous functions and classes.
I stuck on this:
public List<Object> Years { get; set; } = GetYears();
private static List<Object> GetYears()
{
List<Object> retList = new List<Object>();
retList.Add(new { Value = (byte)255, Name = "Any" });
retList.Add(new { Value = (byte)254, Name = "None" });
for (byte i = 0; i < 50; i++)
{
retList.Add(new { Value = i, Name = (2000 + i).ToString() });
}
return retList;
}
Is it possible to get rid of static GetYears() method?
I mean something like this:
public List<Object> Years { get; set; } = () =>
{
List<Object> retList = new List<Object>();
for (byte i = 0; i < 50; i++)
{
retList.Add(new { Value = i, Name = (2000 + i).ToString() });
}
return retList;
}
The problem is that the field initializer cannot reference non-static method.
Is it possible to get around this?
Edit: I added these 2 lines of code:
retList.Add(new { Value = (byte)255, Name = "None" });
retList.Add(new { Value = (byte)254, Name = "Any" });
Technically speaking, you can do something like this
Which creates an anonymous function that returns a
List<Object>, then runs it (unfortunately it cannot be implied, it must be an explicit cast).The much better solution is to just use the constructor, to do pretty much exactly what the constructor exists for.
Funnily enough, the lamda initialization will compile into the constructor anyway, so there is no valid use functionally speaking for defining it outside of the constructor.
See both of these in action here: https://dotnetfiddle.net/1f62Hj