Created
July 27, 2018 15:54
-
-
Save ScottHutchinson/dc7767649bffb572ec322e708b0d84ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Public Interface IHasETN | |
Property ETN As Integer | |
End Interface | |
Public Class Class1 | |
Implements IHasETN | |
Public Property ETN As Integer Implements IHasETN.ETN | |
' Get | |
' Throw New NotImplementedException() | |
' End Get | |
' Set(value As Integer) | |
' Throw New NotImplementedException() | |
' End Set | |
'End Property | |
End Class | |
Public Structure Struct1 | |
Implements IHasETN | |
Public Property ETN As Integer Implements IHasETN.ETN | |
' Get | |
' Throw New NotImplementedException() | |
' End Get | |
' Set(value As Integer) | |
' Throw New NotImplementedException() | |
' End Set | |
'End Property | |
End Structure | |
Public Module Consumer | |
' This function works fine if anArray is always an array of classes that implement the IHasETN interface, | |
' but a call that passes an array of structures will not compile. | |
Public Function FindIndexOfETN(ByVal iETN As Integer, ByVal anArray As IHasETN()) As Integer | |
Return Array.FindIndex(anArray, Function(o) o.ETN = iETN) | |
End Function | |
Public Sub DoStuffWithArraysOfETN() | |
Dim myClass1Array(3) As Class1 | |
myClass1Array(0) = New Class1() | |
myClass1Array(0).ETN = 42 | |
myClass1Array(1) = New Class1() | |
myClass1Array(1).ETN = 45 | |
myClass1Array(2) = New Class1() | |
myClass1Array(2).ETN = 48 | |
Dim classiArrayETNIdx = FindIndexOfETN(48, myClass1Array) | |
Console.WriteLine("classiArrayETNIdx: {0}", classiArrayETNIdx) | |
Dim myStruct1Array(3) As Struct1 | |
myStruct1Array(0) = New Struct1() | |
myStruct1Array(0).ETN = 32 | |
myStruct1Array(1) = New Struct1() | |
myStruct1Array(1).ETN = 35 | |
myStruct1Array(2) = New Struct1() | |
myStruct1Array(2).ETN = 38 | |
'Covariance for interface implementation (i.e. myStruct1Array "is a" IHasETN()) does not work for a structure (value type). | |
'See https://stackoverflow.com/a/12677025/5652483 | |
'Dim structiArrayETNIdx = FindIndexOfETN(48, myStruct1Array) ' --> error BC30311: Value of type 'Struct1()' cannot be converted to 'IHasETN()'. | |
'Console.WriteLine("structiArrayETNIdx: {0}", structiArrayETNIdx) | |
End Sub | |
End Module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment