Basically, I have a function that has an optional dictionary argument. Since it's optional, it needs a default value, and I'd like to set it to an empty dictionary instead of Nothing. How do I go about that?
In Java, I would simply do this:
Collections.<K,V>emptyMap()
How do I do the equivalent in VB.NET?
(I'm using .NET 3.5).
Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply: Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression.
In other words, you can create the argument with a default value so that the user can call the procedure without passing a value for the argument, thus passing a value only when necessary. Such an argument is called default or optional.
With Optional, we can specify a default value and then omit it when calling a method. A syntax change. Optional arguments are a syntax improvement. The VB.NET compiler inserts the default values for an Optional argument in all calling locations.
There isn't a pre-canned empty dictionary in .NET. To create an empty dictionary, just go New Dictionary().
However, I believe you will not be allowed to use this the default value of an optional argument, because it can't be calculated at compile time and put into the DefaultValueAttribute. Instead you will need to overload the function: have one overload that takes the dictionary argument, and one that does not. The latter would just new up an empty dictionary as above, and call the first overload.
There is no way to specify an empty Dictionary as the default value for a parameter in VB.Net. VB.Net only supports values that can be encoded in MetaData and creating a new instance of a Dictionary is not one of them.
One option you do have though is to have an optional value which defaults to Nothing. In the case of Nothing create an empty dictionary. For instance.
Public Sub SomeMethod(Optional ByVal map as Dictionary(Of Key,Value) = Nothing)
if map Is Nothing Then
map = new Dictionary(Of Key,Value)
ENd If
...
End Sub
Depending on the purpose, it might be somewhat more resource-saving (i.e. in terms of memory) if the meant-to-be empty Dictionary is created with a Capacity of 0:
var empty = new Dictionary<string, string>(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With