Reputation: 173
I have a class which I have marked as MustInherit (called BasePage), with a generic method that is marked as MustOverride:
Protected MustOverride Function SaveData(Of T As {BaseClass})(ByVal item As T) As T
What I want to do is force the users of this method to only supply a type of BaseClass, or anything derived from it. Also, when a class derives from BasePage, it should work on only one derived class from BaseClass:
Protected Overrides Function SaveData(Of T As BaseClass)(ByVal item As T) As T
Dim grad As DerivedClass = CType(item, DerivedClass)
Return grad
End Function
However, when I try to do the cast, it flags up the following error:
Value of type 'T' cannot be converted to 'DerivedClass'.
All the documentation I have read suggests that this should work. However, it's not a big problem if it doesn't work, as I can work around by making a non-generic method that only accepts BaseClass.
Any ideas?
Upvotes: 2
Views: 3243
Reputation: 546083
All the documentation I have read suggests that this should work.
On the contrary: it can’t work. The type T
derives from BaseClass
– but nothing in your code tells the compiler that it is convertible to DerivedClass
. For example, it could be of type IndependentlyDerivedClass
which is a sibling of DerivedClass
.
However, the following cast works:
Dim grad As DerivedClass = DirectCast(DirectCast(item, BaseClass), DerivedClass))
Notice that I’m using DirectCast
in place of CType
. This is a best-practice when casting in class hierarchies since DirectCast
only allows such casts (these, and boxing/unboxing conversions) so you minimize the risk of accidentally calling a conversion operator (which can happen when you’re using CType
on non-related types).
Upvotes: 1
Reputation: 5029
You typically do something like this
Public MustInherit Class BasePage(Of T As BaseClass)
Public MustOverride Function Savedata(ByVal Item As T) As T
End Class
Public Class derivedPage
Inherits BasePage(Of DerivedClass)
Public Overrides Function Savedata(ByVal Item As DerivedClass) As DerivedClass
Dim grad As DerivedClass = Item
Return grad
End Function
End Class
Public MustInherit Class BaseClass
End Class
Public Class DerivedClass
Inherits BaseClass
End Class
Upvotes: 1