Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I give a default value to parameters or optional parameters in C# functions?

Tags:

c#

Can I give default parameters in C#?

In C:

void fun(int i = 1) {     printf("%d", i); } 

Can we give parameters a default value? Is it possible in C#? If so, can we avoid overloading functions?

It's always a bad practice to add an optional parameter to an existing function. If you are working on a project which is having to refer the class having a function and we changed a parameter with an optional value, it may throw a run time exception that the method is not found.

This is because we will consider that the if we add an extra optional value, there is no code change required if the function is used in many places.

function Add(int a, int b); 

This will be called using this way:

Add(10, 10); 

But if we add an optional parameter like this,

function Add(int a, int b, int c = 0); 

then the compiler expects

Add(10, 10, 0); 

Actually we are calling like this Add(10, 10) and this function won't be available in that class and causes a run time exception.

This happens for while adding a new parameter to a function which called by a lot of places and I not sure this will happen every time. But I suggest you to overload the function.

Always we need to overload the method which has an optional parameter. Also if you are working with functions having more than one optional parameter, then it's good to pass the value using the name of the parameter.

function Add(int a, int b, int c = 0); 

It's always good to call this function using the following way.

Add(10, 20, c:30); 
like image 530
kbvishnu Avatar asked Oct 12 '10 12:10

kbvishnu


1 Answers

That is exactly how you do it in C#, but the feature was first added in .NET 4.0

like image 139
Chuck Avatar answered Oct 14 '22 17:10

Chuck