How to set a default method for an optional parameter in a method.
I've been trying to google this frantically because I'm sure this question has been asked by others before, but all the results are just for optional parameters in general (and none of the examples are passing methods).
Here's my method example:
All I want is to allow the method to be called without any parameters, in which case condition would just always return true.
Right now I have to call the method like this:
Basically I want the lambda above to be the default value for "condition" in the method. But simply assigning it as the default isn't allowed.
What is the proper syntax for setting a method as a default parameter?
8 Replies
make
condition
be nullable and default it to null
then in the if, just check if its null before invoking it, or default that value to true
thats what I do in my very similar method
that's perfect, thanks!
feel free to borrow the generic nature of this method btw 😛
it works for anything parsable, instead of just for ints
you use it like
var age = GetFromConsole<int>("How old are you?");
or specify int on the left, and it will be inferred on the rightSomething like that was actually gonna be my next step, so thanks a lot!
After rewriting my own code to look be more similar to yours, I have this:
My only concern now is that the value being returned might be null.
Now name the method properly and we're good
oh yeah
I'm not used to C# naming conventions yet 😛
$structure for reference