I was reading up on recent C# features and I found a strange example I though was a mistake.
Essentially, a static method GetFuelCost
was being declared within the body of Main
. I've never seen something like this before.
class Program
{
static void Main(string[] args)
{
var superhero = new Superhero
{
FirstName = "Tony",
LastName = "Stark",
MaxSpeed = 10000
};
static decimal GetFuelCost(object hero) =>
hero switch
{
Superhero s when s.MaxSpeed < 1000 => 10.00m,
Superhero s when s.MaxSpeed <= 10000 => 7.00m,
Superhero _ => 12.00m,
_ => throw new ArgumentException("I do not know this one", nameof(hero))
};
Console.WriteLine(GetFuelCost(superhero)); // 7.00
}
}
I thought this would be a compiler error, but it runs! I can declare a static method within the body of another method and call it just fine. What is this feature called? What practical cases is it intended to solve?