Can I give default parameters in C#?
In C:
void fun(int i = 1)
{
printf(\"%d\", i);
}
Can we give parameters a default value? I
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
{
}
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.
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.
That is exactly how you do it in C#, but the feature was first added in .NET 4.0
This is a feature of C# 4.0, but was not possible without using function overload prior to that version.
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).