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?
On the contrary: it can’t work. The type
Tderives fromBaseClass– but nothing in your code tells the compiler that it is convertible toDerivedClass. For example, it could be of typeIndependentlyDerivedClasswhich is a sibling ofDerivedClass.However, the following cast works:
Notice that I’m using
DirectCastin place ofCType. This is a best-practice when casting in class hierarchies sinceDirectCastonly 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 usingCTypeon non-related types).