r/visualbasic • • Mar 04 '20

VB.NET Help Declare and Instantiate List(Of KeyValuePair(Of String, String))

I am trying to code my own Enigma machine for no reason other than I watched a video on how they work and now I'm intrigued.

I'm trying to make an emulation of the wiring of the rotors and the best thing to do looks like the List(Of KeyValuePair(Of String, String)). I know how to add to it, but I just want to fill it during the declaration instead, as the values won't ever change

Now I know how to do it with a simple list, for example

Public wiring as New List(Of String) ({"A", "B"})

But if I do it like that for KeyValuePair it throws an error

Public wiring as New List(Of KeyValuePair(Of String, String)) ({"A","B"} {"C","D"})

I get an "Overload resolution failed because no accessible 'New' accepts this number of arguments"

How do I do it?

6 Upvotes

6 comments sorted by

2

u/JasonHenley Mar 04 '20

Try this:

Public wiring As New List(Of KeyValuePair(Of String, String))({New KeyValuePair(Of String, String)("A", "B")})

Let's break down why this works. Firstly, you can declare new List(Of String) like this:

Dim foo As New List(Of String)({"A", "B"})

For KeyValuePairs it's different. Note you don't have curly braces.

Dim bar As New KeyValuePair(Of String, String)("A", "B")

Then you just nest the two.

2

u/ste_wilko Mar 04 '20

Excellent thanks!

How would I use more than one set of values?

Like ("A","B") ("C","D")?

1

u/JasonHenley Mar 04 '20

You edited your original post after I replied. If you want two KeyValuePairs in your list, do this:

Public wiring As New List(Of KeyValuePair(Of String, String))({New KeyValuePair(Of String, String)("A", "B"), New KeyValuePair(Of String, String)("C", "D")})

2

u/ste_wilko Mar 04 '20

You're an absulute legend, thanks!

1

u/f15sim Mar 26 '20

Why not use a Dictionary instead?