So one of the things you find in C# when you move from VB.NET is that you can’t do Optional parameters on methods.

Actually, you can – it’s just that the compiler in VB.NET is giving you a free ride by generating overloaded values for you automatically. Correction, Looks like C# is being difficult, see this FAQ

Anyway, say you have a VB.NET function like so:

Public Sub TestFunction(Param1 as String, Optional Param2 as String = “Default Value”)
    // Do Stuff
End Sub

In C# you can achieve the same thing by writing a stub like so:

public void TestFunction(string Param1)
{
TestFunction(Param1, “Default Value”);
}

public void TestFunction(string Param1, string Param2)
{
// Do Stuff
}

Yeah, it’s a little more code to write – but it’s really not that difficult to manage unless you have truely obscene numbers of optional parameters.

TechRepublic has a look at the same issue too, and gives Parameter arrays as an alternative. Under .NET 3.0+ with Anonymous types you can use some reflection niceties to do some other, similar things too.

On a different note, reading VB code after nearly a year straight of C# development feels a little strange.

Comments are closed.