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

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);

This question is related to c#

The answer is


It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).


Yes. See Named and Optional Arguments. Note that the default value needs to be a constant, so this is OK:

public string Foo(string myParam = "default value") // constant, OK
{
}

but this is not:

public void Bar(string myParam = Foo()) // not a constant, not OK
{
}

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.


This functionality is available from C# 4.0 - it was introduced in Visual Studio 2010. And you can use it in project for .NET 3.5. So there is no need to upgrade old projects in .NET 3.5 to .NET 4.0.

You have to just use Visual Studio 2010, but remember that it should compile to default language version (set it in project Properties->Buid->Advanced...)

This MSDN page has more information about optional parameters in VS 2010.


Yes, but you'll need to be using .NET 3.5 and C# 4.0 to get this functionality.

This MSDN page has more information.