Default method parameters in C#

前端 未结 4 378
栀梦
栀梦 2021-01-11 15:47

How can I make a method have default values for parameters?

4条回答
  •  情话喂你
    2021-01-11 16:08

    You can only do this in C# 4, which introduced both named arguments and optional parameters:

    public void Foo(int x = 10)
    {
        Console.WriteLine(x);
    }
    
    ...
    Foo(); // Prints 10
    

    Note that the default value has to be a constant - either a normal compile-time constant (e.g. a literal) or:

    • The parameterless constructor of a value type
    • default(T) for some type T

    Also note that the default value is embedded in the caller's assembly (assuming you omit the relevant argument) - so if you change the default value without rebuilding the calling code, you'll still see the old value.

    This (and other new features in C# 4) are covered in the second edition of C# in Depth. (Chapter 13 in this case.)

提交回复
热议问题