简体   繁体   中英

What is the idiomatic naming convention for local functions in C# 7

Normal class methods, whether instance or static, have an idiomatic naming convention with regards to their casing. It's not clear that there is a convention for local functions , introduced in C# 7.

Should a local function be named in camelCase ?

public static int Factorial(int n)
{
    return calcFactorial(n);

    int calcFactorial(int number) => (number < 2)
        ? 1
        : number * calcFactorial(number - 1);
}

Or PascalCase ?

public static int Factorial(int n)
{
    return CalcFactorial(n);

    int CalcFactorial(int number) => (number < 2)
        ? 1
        : number * CalcFactorial(number - 1);
}

My standard is always PascalCase, also spell out the full word. I don't like abbreviations as they can have multiple meanings.

So, in your PascalCase scenario, I would spell out the 'Calc' word to be the following:

public static int Factorial(int n)
{
    return CalculateFactorial(n);

    int CalculateFactorial(int number) => (number < 2)
        ? 1
        : number * CalculateFactorial(number - 1);
}

Compilers have come along ways, and a few extra bytes to make it clear what the method does is worth the few extra keystrokes.

There's no "right" answer to this.

But in our team we're using _PascalCase() for local functions.

We already use _xxx for private variables, and having an underscore before the function name makes it obvious it's local (like it's "private"). And having PascalCase helps distinguish functions from variables. Also very handy when working with non Visual Studio but basic text editors.

public static int Factorial(int n)
{
    return _CalcFactorial(n);

    int _CalcFactorial(int number) => (number < 2)
        ? 1
        : number * _CalcFactorial(number - 1);
}

PS SO's syntax highlighter does not like this though :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM