Brett Allen
Brett Allen

Reputation: 5477

Is it possible to have a generic default property in VB.NET?

I'm attempting the following:

Default Public Property Data(Of dataType)(ByVal key As String) As dataType
  Get
    Return DirectCast(values.Item(key), dataType)
  End Get
  Set(ByVal value As dataType)
    values.Item(key) = value
  End Set
End Property

values is type Dictionary(Of String, Object) but we have another lookup Dictionary with data types associated to the keys.

Of course this refuses to compile, with the squiggly line under (Of dataType) due to:

Type parameters can not be specified on this declaration.

Is this not possible, or am I just doing it wrong?

Edit: Essentially I'm trying to make this a property, so that I don't have to do the following.

Public Function GetData(Of dataType)(ByVal key As String) As dataType
  Return DirectCast(values.Item(key), dataType)
End Function

Public Sub SetData(ByVal key As String, ByVal value As Object)
  values.Item(key) = value
End Sub

It made more sense to make it a property, and it would be the default property of the class. The data type can not be specified on instantiation of the class, because it can contain multiple objects of different data types.

Upvotes: 2

Views: 1443

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460028

No, i think generic properties are not(and won't) possible in .Net. This So-Answer clarifies why the compiler must know the type on compile-time: Can I have generics in a Class Property?

[copied from comments]

Upvotes: 2

Related Questions