C# Language Default Parameters


Example

You can use default parameters if you want to provide the option to leave out parameters:

static void SaySomething(string what = "ehh") {
    Console.WriteLine(what);
}  

static void Main() {
    // prints "hello"
    SaySomething("hello"); 
    // prints "ehh"
    SaySomething(); // The compiler compiles this as if we had typed SaySomething("ehh")
}

When you call such a method and omit a parameter for which a default value is provided, the compiler inserts that default value for you.

Keep in mind that parameters with default values need to be written after parameters without default values.

static void SaySomething(string say, string what = "ehh") {
        //Correct
        Console.WriteLine(say + what);
    }

static void SaySomethingElse(string what = "ehh", string say) {
        //Incorrect
        Console.WriteLine(say + what);
    }   

WARNING: Because it works that way, default values can be problematic in some cases. If you change the default value of a method parameter and don't recompile all callers of that method, those callers will still use the default value that was present when they were compiled, possibly causing inconsistencies.