ruedi
ruedi

Reputation: 5545

How to create a Dictionary(TKey, TValue) property

I try to create a property that holds a dictionary.

Private _dic As Dictionary(Of String, Decimal)
Public Property DicProp(ByVal val1 As Decimal, ByVal val2 As Decimal,
                          ByVal val3 As Decimal) As Dictionary(Of String, Decimal)
    Get
        Return _dic
    End Get
    Set(value As Dictionary(Of String, Decimal))
        value.Add("Value1", val1)
        value.Add("Value2", val2)
        value.Add("Value3", val3)
    End Set
End Property

I tried to fill the property with

        .DicProp(1,2,3)

But I get the message "Property access must assign to the property or use its value". Could anyone help me get this working?

Upvotes: 0

Views: 259

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415620

Delete the Set section of the property entirely:

Private _dic As New Dictionary(Of String, Decimal)
Public Property DicProp As Dictionary(Of String, Decimal)
    Get
        Return _dic
    End Get
End Property

You will still be able to make changes to this property, even without a setter!

MyObject.DicProp.Add("Value1", 1.0D)
MyObject.DicProp.Add("Value2", 2.0D)
MyObject.DicProp.Add("Value3", 3.0D)

This works, because it's equivalent to this code:

Dim temp As Dictionary(Of String, Decimal)
temp = MyObject.DicProp ' Use the *Get* portion of the property in your object to retrieve the dictionary
temp.Add("Value1", 1.0D) ' Then use the Add (or Set properties) on the retrieved dictionary object

Upvotes: 1

Magnus
Magnus

Reputation: 46909

You want a function (or Sub in this case for VB) not a property as properties can only get or set a single value.

Public Sub AddValues(ByVal val1 As Decimal, ByVal val2 As Decimal, ByVal val3 As Decimal)
   _dic.Add("Value1", val1)
   _dic.Add("Value2", val2)
   _dic.Add("Value3", val3)
End Sub

And then:

AddValues(1,2,3)

Upvotes: 1

Related Questions