jeonggu
jeonggu

Reputation: 111

I want to get the generic dictionary as return value of function in vb.net

I want to get the generic dictionary as return value of function in vb.net.

How can I get this?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim buttons As Dictionary(Of Integer, Button) = generateControls(Of Button)(3)
    Dim textBoxes As Dictionary(Of Integer, TextBox) = generateControls(Of TextBox)(3)

End Sub

Private Function generateControls(Of T)(repeat As Integer) As Dictionary(Of Integer, T)
    Dim dic As New Dictionary(Of Integer, T)

    For i As Integer = 0 To repeat - 1
        Dim control As New T
        dic.Add(i, control)
    Next
    Return dic

End Function

Upvotes: 0

Views: 582

Answers (1)

FloatingKiwi
FloatingKiwi

Reputation: 4506

You need to specify a type constraint declaring that the type has a default constructor.

Use generateControls(Of T As New) instead of generateControls(Of T)

However I prefer:

    Dim result = Enumerable.Range(0, 3).
                            ToDictionary(Function(i) i, Function(i) New TextBox() With {... })

Upvotes: 2

Related Questions