Reputation: 5661
We have this:
Friend NotInheritable Class ConcreteGraphFactory
Inherits AbstractGraphFactory
Public Shared ReadOnly Instance As New ConcreteGraphFactory()
Private Sub New()
MyBase.New()
End Sub
Friend Overrides Function Create() As AbstractGraph
Return New ConcreteGraph()
End Function
Private NotInheritable Class ConcreteGraph
Inherits AbstractGraph
Private ReadOnly Question1 As New Question("Why isn't this showing a warning?")
Public Overrides Function GetRoot() As IRoot
Return Question1 '<---HERE
End Function
Public Sub New()
End Sub
End Class
End Class
And I have IRoot
:
Friend Interface IRoot
Inherits IQuestion
Function GetContainer() As AbstractGraph
End Interface
And finally Question
:
Public Class Question
Implements IQuestion
' code....
End Class
Why would VS not show a warning? Question
does not implement IRoot
...
Upvotes: 4
Views: 97
Reputation: 13837
If you want the compiler to give an error there, then you need to set Option strict to On. You can do that on the Compile tab of the project's Properties. Or add Option Strict On
to the top of the file that contains this code.
Here are a few pages that have more details about what Option Strict means.
http://support.microsoft.com/en-us/kb/311329
https://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx
Option Strict Off means that the Visual Basic compiler doesn't enforce strict data typing. It will try to do implicit type conversions and throw run time errors if that can't be done.
I didn't think it had anything to do with IRoot
being an interface, but after trying it out it looks like it does. If GetRoot
returned a class that Question
didn't inherit from, then you would get a compiler error even with Option Strict off.
Running with Option Strict off actually makes some things easier, especially when dealing with late bound COM objects. For the most part, you don't have to worry about type casts when writing code.
However, it's also one of the reasons many people don't like VB.NET. Personally, I liked it when I was working with it, but it's been long enough now that it does seem strange that the compiler wouldn't be doing all the strict type checking for you. I could always tell when some VB code had been generated via a conversion tool from C# because it would have a bunch of DirectCast
calls that you wouldn't see in code that a VB developer had written.
When C# came out with the dynamic
keyword in 2009, the VB.NET developers were thinking, "Meh. We've always been able to write code without worrying about types." Of course, VB.NET wasn't the same as dynamic
in C#, but many of the early dynamic code examples were showing things that you could already do in VB with option strict turned off.
Upvotes: 4