pitoloko
pitoloko

Reputation: 95

How to create a Dictionary type with default values?

Can I create a dictionary with default values instead of needing to add the values from a procedure?

I'd like to do something like this:

Dim MyDict As New Dictionary(Of Int64, Boolean) { (1, True), (2, False) } 

Instead of this:

Dim MyDict As New Dictionary(Of Int64, Boolean)

private sub blablabla
     MyDict.Add(1, True)
     MyDict.Add(2, False)
end sub

Upvotes: 1

Views: 105

Answers (1)

zastrowm
zastrowm

Reputation: 8243

Collection initializers allow you to add values when you creation the dictionary:

Dim MyDict As As New Dictionary(Of Int64, Boolean) From {{1, True}, {2, False}}

The cool thing is that it works with lists and other classes as well. You can even use this in your own classes by implementing IEnumerable and having an Add method (the documentation explains all of this in more detail).

Upvotes: 2

Related Questions