Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Parameter Value to Another Parameter

Tags:

c#

I would like to do something like below:

private void MyMethod(int param1, int param2 = param1){}

The intent is to make param2 optional, and where it is not specified, give it the same value as the first parameter.

Is this possible?

I am aware that I can use nullable types and do the check and assignment in the method body. I also know I could achieve this through overloading. I specifically want to know if this is possible in the signature.

I'm using .Net 4.0

Thanks

like image 342
GinjaNinja Avatar asked Aug 01 '26 23:08

GinjaNinja


1 Answers

Is this possible?

No. Default values for parameters have to be one of:

  • A compile time constant (e.g. a numeric or string literal)
  • The default value for the parameter type, e.g. default(Foo) or default (as of C# 7.1)
  • The "zero" values of value types, e.g. new Guid()

It's quite restrictive, unfortunately.

like image 163
Jon Skeet Avatar answered Aug 04 '26 14:08

Jon Skeet