1

I have a function as follows:

Function foo(ByVal c As CustomType, ByValue str as String) As Object
   Dim o as Object
   Select Case c.TypeName
     Case "System.String"
       If str = String.Empty Then
         o = DBNull.Value
       Else
         o = value
       End If
     Case "System.Int64"
       Try
         o = Long.Parse(value, Globalization.NumberStyles.Any)
       Catch
         o = DBNull.Value
       End Try
     Case "System.Double"
       Try
         o = Double.Parse(value, Globalization.NumberStyles.Any)
       Catch
         o = DBNull.Value
       End Try
     Case "System.Int32"
       Try
         o = Int32.Parse(value, Globalization.NumberStyles.Any)
       Catch
         o = DBNull.Value
       End Try
     Case "System.DateTime"
       Try
         o = DateTime.Parse(value)
       Catch
         o = DBNull.Value
       End Try
   Return o
End Function

This function makes me want to write a generic version. Since partial specialization is not allowed in .NET like C++ (please correct me if i am wrong here), what are the various ways in which i can use whatever features of generics are there. I gave an embarrassing try but failed:

Function foo(Of T)(...) as Object
  Dim o As Object
  Try
     o = T.Parse(...) 'This doesnt work
  Catch
     o = DBNull.Value  
  End Try  
  ...
End Function
'Add functions for handling String and DateTime maybe?
2
  • Why would an invalid string result in DBNull? That sounds like a bad design choice, IMO. In fact, unless this is directly related to (say) sql parameter packing, I have no idea why DBNull should be involved at all. Commented May 2, 2012 at 5:39
  • This is indeed related to SQL parameter packing. Commented May 2, 2012 at 5:42

2 Answers 2

3

Indeed, you can't use T.whatever with generics; only instance methods of T (based on the known constraints of T) may be employed.

Maybe something like:

// return object since SQL parameter packing
static object Parse<T>(string value)
{
    if (string.IsNullOrEmpty(value)) return DBNull.Value; // for SQL parameter
    return TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}

?

Sign up to request clarification or add additional context in comments.

Comments

1

You can simplify your code somehow using reflection:

If c.Type.Primitive Then
   o = c.Type.GetMethod("Parse").Invoke(Nothing, New Object() {value, Globalization.NumberStyles.Any}) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.