VB Quark #7 : Optional Parameters and Dates
Wed, Nov 9 2011 14:14
Hopefully you already know VB has full support for Optional parameters, both declaring them and calling them, but did you know you can use Dates as Optional parameters ? Public Sub AddNewCustomer(customer As Customer,
Optional dateAdded As Date = Nothing)
If dateAdded = Nothing Then dateAdded = Now
VB has had this support for Optional parameters in place for the last decade or so in .NET and for years before that back in the COM versions of VB.
In the last release of .NET (VS 2010), C# finally got support for Optional parameters, so the above in C# would look like: public void AddNewCustomer(Customer customer,
DateTime dateAdded = default(DateTime))
if (dateAdded == default(DateTime)) dateAdded = DateTime.Now;
The Nothing in the VB declaration is the same as default(DateTime) in C#, which equates to the theoretical Gregorian date of 1/1/0001.
But what if you want to specify a default date ? Well because VB supports date literals, in VB you can, but in C# you can’t. In VB you can write any date literal for the optional parameter value. For example, you might have some legacy database support, and when the date is unknown you want to use the equivalent of an OLE Date’s zero value: Public Sub AddNewCustomer(customer As Customer,
Optional dateAdded As Date = #12/30/1899#)
When the VB compiler compiles this, it adds a System.Runtime.CompilerServices.DateTimeConstantAttribute to the parameter information with the default value stored as an Int64 (the number of ticks). C# actually sees the optional value in the above example and will use it. That is both VB and C# can call the code taking advantage of the optional value for the date parameter, but only VB let’s you define that value.