views:

626

answers:

2

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

+5  A: 

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.

itowlson
+3  A: 

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
JaredPar
Thanks, this also worked for me with ...(Optional ByRef myVar() as Double = Nothing). I was stuck figuring out how to specify the default values of my array until I ran across 'Nothing' in your answer.
Stewbob