1

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?

MoSlo
  • 535
  • 5
  • 11
  • 2
    This is called [Local Functions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions). Practical cases: you have some repeating/big chunk of logic in the method, but this chuck can't be logically separated into the other method. Also local functions allow you to reference outter variables defined in the method it's declared in, like in JS. – Neistow Dec 31 '21 at 17:43
  • It's called local functions: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions – Sasha Dec 31 '21 at 17:43
  • 1
    It's a local function, which is a recent addition (static local is even more recent). For when you want to encapsulate some code, but don't want a real method, even private – Hans Kesting Dec 31 '21 at 17:43
  • 2
    Watch out for the oddity that (unlike local variables) you can use them "before you've declared them", in case you're looking at some code and seeing `GetFuelCost` and you're thinking "what is this? where is it?" - it could be at the bottom of the method; they aren't subject to the same "declaration must appear nearer the top of the source code than the use" - just like regular methods, really (so it's logical, but..) – Caius Jard Dec 31 '21 at 17:47
  • 2
    https://stackoverflow.com/questions/40943117/local-function-vs-lambda-c-sharp-7-0 is useful reading – Caius Jard Dec 31 '21 at 17:51

0 Answers0