Search code examples
c#.netsyntax

C# syntax - usage of : operator


Browsing the .Net source code, I came across the below method. My question is about the syntax used when calling EqualStartingCharacterCount(). What is the purpose of the : in the parameter list? What is this syntax called?

internal static int GetCommonPathLength(string first, string second, bool ignoreCase)
{
    int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase);

    // If nothing matches
    if (commonChars == 0)
        return commonChars;

    // Or we're a full string and equal length or match to a separator
    if (commonChars == first.Length
        && (commonChars == second.Length || IsDirectorySeparator(second[commonChars])))
                return commonChars;

    if (commonChars == second.Length && IsDirectorySeparator(first[commonChars]))
        return commonChars;

    // It's possible we matched somewhere in the middle of a segment e.g. C:\Foodie and C:\Foobar.
    while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1]))
                commonChars--;

    return commonChars;
}

Another example where the : is used.

public static string[] GetDirectories(string path) => GetDirectories(path, "*", enumerationOptions: EnumerationOptions.Compatible);

Solution

  • This is syntax allowing to provide a named argument. From the specification (12.6.2 Argument lists):

    argument_list
        : argument (',' argument)*
        ;
    
    argument
        : argument_name? argument_value
        ;
    
    argument_name
        : identifier ':'
        ;
    
    argument_value
        : expression
        | 'in' variable_reference
        | 'ref' variable_reference
        | 'out' variable_reference
        ;
    

    Each argument consists of an optional argument_name followed by an argument_value. An argument with an argument_name is referred to as a named argument, whereas an argument without an argument_name is a positional argument.

    On the left of : is the name of method parameter

    It can be used to "reorder" method parameters:

    int Do(int left, int right) => left;
    
    Console.WriteLine(Do(right: 1, left: 0)); // Prints 0
    

    "skip" optional parameters:

    int Do(int one = 1, int two = 2, int three = 3) => three;
    
    Console.WriteLine(Do(three: 4)); // Prints 4
    

    Or just improve the readability of the code which seems to be the case of the provided EqualStartingCharacterCount call if I correctly found it in the source code

    See also the Named arguments section of the docs.