Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default parameter values in C#'s lambda expressions

Tags:

c#

lambda

Good afternoon,

Can someone please tell me if I can set default parameter values when using lambda expressions in C#? For example, if I have the code

public static Func<String, Int32, IEnumerable<String>> SomeFunction = (StrTmp, IntTmp) => { ... },

how can I set IntTmp's default value to, for example, two? The usual way to set default parameter values in a method seems not to work with this kind of expressions (and I really need one of this kind here).

Thank you very much.

like image 703
Miguel Avatar asked Oct 21 '10 13:10

Miguel


People also ask

What is default parameter in C?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

What is a default parameter value?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Can you have default parameters in C?

There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.

Can parameters have default values?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.


1 Answers

You really cannot unless you do it via composition of functions:

public static Func<String, Int32, IEnumerable<String>> SomeFunction = 
                                          (StrTmp, IntTmp) => { ... };

public static Func<String, IEnumerable<String>> SomeFunctionDefaulted =
                                  strTmp => SomeFunction(strTmp, 2);

You could also try modifying SomeFunction to take a nullable, but then you would have to explicitly pass null for a value and check for that in the method body.

like image 75
Philip Rieck Avatar answered Sep 28 '22 23:09

Philip Rieck