views:

46

answers:

2

I have a Class that is defined as

Public MustInherit Class Entity(Of T As Entity(Of T))

And various classes derived from it. I would like to have another class accept all of the derived objects as a property, but I cannot seeem to find a workable syntax. If it were a parameter of a sub, I could say

Public Sub Foo(T As Entity(Of T))(TheEntity As T)

I can't seem to get that to work for a property:

Public Property E(Of Entity(Of T))() As Entity(Of T)

Gives me "Type parameters cannot be specified on this declaration"

Public Property E() As Entity2008(Of T)

Gives me "Type Parameter T does not inherit from or implement the constraint type ..."

Is there an acceptable way to do this or am I stuck with using a Set Sub and a Get Function?

A: 

.NET support only the generic property for a generic class parameter, doesn't support an independ*. That you are creating with E

This ability is for methods only. Properties or indexers can only use generic type parameters defined at the scope of the class.

http://msdn.microsoft.com/en-us/library/ms379564 (Generic Methods)

* not in the scope of the class.

Vash
What does "an independ. That you are creating with E" mean? Please revise your comment to make sense.
Gabe
@Gabe revised. it its Ok ?
Vash
I still don't understand it.
Gabe
A: 

To declare the property, the compiler needs to know at compile time what the type would be. (This is something methods can do, that properties cannot).

Consider the case where you were data binding an IEnumerable(Of yourtype) to a DataGridView, which will enumerate all the properties and make a column for each. When it hits the hypothetical generic property, it has no information for which type to substitute.

Consider the case where you've got an instance of your class, and you set your E property -- it would be possible to set two properties with two different signatures, maybe one as:

foo.E(Of Entity(Of Byte)) = New Entity(Of Byte)

And another as:

foo.E(Of Entity(Of Guid)) = New Entity(Of Guid)

So, should they set different properties? Should setting one signature set the value for the other? Obviously in the case above, the types are not convertible to each other.

There is nothing to stop you from doing:

Public MustInherit Class Entity(Of T As Entity(Of T))
    Public Property E() As Entity(Of T)
        Get
            Throw New NotImplementedException()
        End Get
        Set
            Throw New NotImplementedException()
        End Set
    End Property
End Class

And in this case, you could only ever have the same type for the Entity and its E property would have to be of the same type as itself (Unless you decorate for variance)

Rowland Shaw