Constrain generic extension method to base types and string

Posted by hitch on Stack Overflow See other posts from Stack Overflow or by hitch
Published on 2010-05-14T00:44:22Z Indexed on 2010/05/14 0:54 UTC
Read the original article Hit count: 313

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

© Stack Overflow or respective owner

Related posts about generic

Related posts about Constraint