How to use default parameters in C#?
15,882
Solution 1
At present, you have to overload the method:
void cookEgg(bool hardBoiled) { ... }
void cookEgg() { cookEgg(true); }
C# 4.0 will add optional arguments - you will be able to write code exactly as in your original sample, and it will work as you'd expect.
Solution 2
Default parameters are supported in C# 4 (Visual Studio 2010).
http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx
Solution 3
This is not what you look exactly but I think params argument is another answer.
void test(params int []arg) { }
Related videos on Youtube
Author by
Chin
Updated on April 19, 2022Comments
-
Chin about 2 years
In other languages I can set up the method signature like
cookEgg(boolean hardBoiled = true)
This defaults the parameter
hardboiled
totrue
, if I don't receive a parameter in the method call.How would I achieve this in C#?
-
Zack almost 15 yearsI'm looking forward to this feature tbh. Rather annoying to have to make an overloaded method to have this feature at the moment. I'm also hoping for static extension methods (extending a static class, like... System.String or something).
-
Pavel Minaev almost 15 yearsI must be missing something, as you can easily define extension methods for
System.String
in C# 3.0.