badmaash
badmaash

Reputation: 4845

VB.NET Generics

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?

Upvotes: 1

Views: 416

Answers (2)

user694833
user694833

Reputation:

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}) 

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062540

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);
}

?

Upvotes: 3

Related Questions