Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# default parameters workaround

Is there a workaround for default parameters? In C++ I would use

int foo(int k, bool check = false)

A tedious workaround would be to overload a function. An easier one? (There is no way just adding the variable and checking the calls of the function!!)

Thanks, Sun

like image 688
Sunscreen Avatar asked Nov 30 '22 04:11

Sunscreen


1 Answers

The C# (before 4.0) didn't support the default parameters. Even in c# 4.0 the default parameters are a bit different than in C++ - they're stored in metadata and, when you reference the assembly with default parameters, they're compiled into your code. So, if the default value was changed in the future, your code will still pass the OLD default value, which may cause the bad effect. So, use the overloaded functions with a single parameter and double parameters and call the one with more parameters passing the default value. Such approach will have a least side effect.

like image 115
Denis Mazourick Avatar answered Dec 11 '22 05:12

Denis Mazourick