I’m trying to create a generic IsEmpty extension but am having problems specifically with dictionaries:
The functions I have created:
<Extension()> Function IsEmpty(null As DBNull) As Boolean
Return True
End Function
<Extension()> Function IsEmpty(d As Date) As Boolean
Return d = New Date
End Function
<Extension()> Function IsEmpty(s As String) As Boolean
Return s Is Nothing OrElse s.Length = 0
End Function
<Extension()> Function IsEmpty(a As Array) As Boolean
Return a Is Nothing OrElse a.Length = 0
End Function
<Extension()> Function IsEmpty(collection As ICollection) As Boolean
Return collection Is Nothing OrElse collection.Count = 0
End Function
<Extension()> Function IsEmpty(Of T)(val As T) As Boolean
Return False
End Function
For my purposes, booleans and numerics are never “empty”.
The problem is that dictionaries are using the generic (Of T)(val As T) function instead of the (collection As ICollection) function.
i.e.
Dim dict As New Dictionary(Of String,String)
Response.Write(dict.IsEmpty)
output is “False”
I tried using (Of K,V)(collection As ICollection(Of KeyValuePair(Of K,V))) to no avail.
What am I doing wrong?
The problem is that your overload:
becomes more specific than:
The compiler will choose the generic overload first, because it can specify
Tto be aDictionary(of String, String)which is more specific than anICollection. If you change the generic method to simply take an object, theICollectionoverload will be more specific, and be selected by the compiler: