Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty dictionary for optional argument in VB.NET

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

like image 250
cdmckay Avatar asked Apr 09 '09 05:04

cdmckay


People also ask

How do you declare an optional parameter in VB?

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.

What are optional arguments in VB?

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.

What is the use of optional argument in VB net?

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.


3 Answers

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.

like image 82
itowlson Avatar answered Oct 19 '22 01:10

itowlson


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
like image 41
JaredPar Avatar answered Oct 19 '22 01:10

JaredPar


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);
like image 25
Nico Avatar answered Oct 19 '22 02:10

Nico