Different return and declared function type result, With Strict Mode Off

142 Views Asked by At

i have a project which runs with strict mode off and this code.

Public Overloads Function Save() As Child
     Return MyBase.Save()
End Function

Upon turning strict mode on, an error displays:

Option Strict On disallows implicit conversions from 'Parent' to 'Child'.

My question is the parent's save that is being executed OR the child's as the parent's object is being cast to the child's type?

Long Version with all the details:

I am trying to understand what this code exactly does to reproduce it clearly in the VB, so it can be clearly ported to C#.

The project is using CSLA, there is a base object, which is inherited from the Parent of the child. Child inherits Parents which inherits Base.

There is Insert at both the child & the parent. Are both of those called, by that weird difference of the return object and the function's type?

2

There are 2 best solutions below

0
Rockford Lhotka On BEST ANSWER

If you are trying to have Parent subclass Csla.BusinessBase, and then have Child subclass Parent, you need to implement Parent like this:

Public Class Parent(Of T)
    Inherits BusinessBase(Of Parent(Of T))

End Class

Public Class Child
    Inherits Parent(Of Child)

    Protected Overrides Function SaveAsync(forceUpdate As Boolean, userState As Object, isSync As Boolean) As Task(Of Parent(Of Child))
        Return MyBase.SaveAsync(forceUpdate, userState, isSync)
    End Function
End Class

This allows the generic type T to flow from up through the inheritance hierarchy such that the implementation of SaveAsync (or Save in older versions of CSLA) is of type Child.

4
Joel Coehoorn On

The Child's save function is called, but the MyBase keyword within that function invokes the parent function. It seems the parent version of the Save() function has a return type of Parent. So it's as if you had this code:

Public Overloads Function Save() As Child
    Dim result As Parent = MyBase.Save()
    Return result
End Function

It's not allowed to return an object of one type, when a function is declared to return a different type... unless, as the error message tells you, there is an implicit conversion defined between the two types. Inheritance does not guarantee that conversion.

Mismatched returns can cause things to blow up at runtime. This kind of thing is exactly why you should always have Option Strict On. It will help you do a better job getting inheritance types right.

Presumably, when Child inherits Parent, it adds its own fields, properties, or methods. At least, that's the usual reason for inheritance. So now you attempt to return an object without any of that extra stuff to a caller that doesn't know it's missing. That's a recipe for disaster.

You can sort-of fix this by adding a Cast() to the code above, but because of the issues described here it might be better to re-write this to use composition instead of inheritance.