Reputation: 18600
I have an interface like so:
Public Interface IDescriptionIdentityPair
Property Id() As String
Property Description() As String
End Interface
I have a class like so:
Public Class DescriptionIdentityPair : Implements IDescriptionIdentityPair
Public Property Id As String Implements IDescriptionIdentityPair.Id
Public Property Description As String Implements IDescriptionIdentityPair.Description
Public Overrides Function ToString() As String
Return Description
End Function
End Class
I have a method like so:
Public Shared Function AddEmptyRow(Of T As IDescriptionIdentityPair)(ByVal collection As IList(Of T)) As IList(Of T)
Dim AddEmptyRowToCollection = collection
collection.Insert(0, New DescriptionIdentityPair With {.Id = "", .Description = FxApplication.DefaultText})
Return collection
End Function
I am getting a compile time error when trying to insert the new instance of the DescriptionIdentityPair class, that the value of type "DescriptionIdentityPair" cannot be converted to T. I even tried casting the DescriptionIdentityPair to it's interface (in desperation), but that did not resolve the issue.
Upvotes: 1
Views: 920
Reputation: 125610
Error is correct. Consider a situation when you have another class implementing your interface:
Public Class AnotherDescriptionIdentityPair : Implements IDescriptionIdentityPair
And you call your generic method with T = AnotherDescriptionIdentityPair
:
Dim list As New List(Of AnotherDescriptionIdentityPair)
AddEmptyRow(list)
What would happen when you tried adding instance of DescriptionIdentityPair
to List(Of AnotherDescriptionIdentityPair)
?
You can fix that addint New
generic constraint to your method and initializing New T
instead of New DescriptionIdentityPair
:
Public Shared Function AddEmptyRow(Of T As {New, IDescriptionIdentityPair})(ByVal collection As IList(Of T)) As IList(Of T)
Dim AddEmptyRowToCollection = collection
collection.Insert(0, New T With {.Id = "", .Description = "DefaultDescription"})
Return collection
End Function
Upvotes: 3