Found something that I was interested in, and I would have liked the explanation.
Edit
In this question there should be no answer what needs to be done to correct it. I know the fixes. I want to explain why the compiler does what it does. Ex. Are private functions considered in the light of this scenario?
Problem
I have a class that has a publicly shared (static) function called WhatIs. WhatIs accepts a parameter that has a set of objects. the code iterates over this collection and calls the WhatIs function, which has the type of matching parameter, what the object is.
On execution, an InvalidCastException is thrown because the execution tries to call the WhatIs function that launched it, and not the one that was provided.
This is strange, but it was strange for me when you changed private general functions to general, and then worked perfectly.
Even clearer when explicitly casting an object, it works even if the function is private.
What?! someone explain
code
guts:
Public Class House Public Property Furniture As ICollection(Of Object) Public Sub New() Furniture = New List(Of Object) End Sub End Class Public Class Chair Public Property IsComfortable As Boolean End Class Public Class Table Public Seats As Integer End Class Public Class HouseExaminer Public Shared Function WhatIs(thing As House) As String Dim isA As String = "a house that contains " For Each item In thing.Furniture isA &= WhatIs(item) Next Return isA End Function Private Shared Function WhatIs(thing As Chair) As String Return "a " & If(thing.IsComfortable, "comfortable", "uncomfortable") & " chair " End Function Private Shared Function WhatIs(thing As Table) As String Return "a table that seats " & thing.Seats & " iguanas" End Function End Class
check
Imports System.Text Imports Microsoft.VisualStudio.TestTools.UnitTesting Imports stuff <TestClass()> Public Class HouseExaminerTests <TestMethod()> Public Sub TestWhatIs() Dim given As New House() Dim expected As String Dim actual As String given.Furniture.Add(New Chair() With {.IsComfortable = True}) given.Furniture.Add(New Table() With {.Seats = 4}) expected = "a house that contains a comfortable chair a table that seats 4 iguanas" actual = HouseExaminer.WhatIs(given) Assert.Equals(expected, actual) End Sub End Class
result
debug the test, and you get the following: InvalidCastException The method error is caused by the "Public Shared Function WhatIs (thing like stuff.House) because String cannot be called with these arguments:
The parameter of coincidence of arguments of the “thing” cannot be transformed from the “chair” to “home”.
These changes make it work, but why ?!
make em public
change your personal shared features in HouseExaminer to a public, retest. spoiler, it works
obviously throws objects
change them to private then replace
isA &= WhatIs(item)
with
If TypeOf item Is Chair Then isA &= WhatIs(CType(item, Chair)) If TypeOf item Is Table Then isA &= WhatIs(CType(item, Table))
retest and what do you know it works