Constrain generic extension method to base types and string
- by hitch
I want to have an extension method for XElement/XAttribute that allows me to apply a "ValueOrDefault" logic - perhaps with various slightly different implementations: ValueOrNull, ValueOrDefault, NumericValueOrDefault (which validates if the value is numeric), but I want to constrain these methods so that they can only work with ValueTypes or String (i.e. it does not really make sense to use any other reference types. Is it possible to do this with one implementation of each method, or will I have to have one where the constraint is "Structure" and one where the constraint is "String" - if I combine Structure and String in the generic constraint, I get the error :
'Structure' constraint and a specific class type constraint cannot be combined.
An example of the current method implementation is as follows:
<Extension()> _
Public Function ValueOrDefault(Of T As {Structure})(ByVal xe As XElement, ByVal defaultValue As T) As T
If xe Is Nothing or xe.Value = "" Then
Return defaultValue
End If
Return CType(Convert.ChangeType(xe.Value, GetType(T)), T)
End Function