webworm
webworm

Reputation: 11019

Returning Generic type in VB.NET

Someone (w69rdy) in Stack Overflow helped me out with a great example to handle DB output, that could potentially be NULL, passed into a function. The problem is I can understand the method as written in C# but I am having a problem understanding how to rewrite the method in VB.NET. The method uses generics and I am lost. Here is the method written in C# ..

 public T ParseValue<T>(System.Data.SqlClient.SqlDataReader reader, string column)
 {
     T result = default(T);

     if (!reader.IsDBNull(reader.GetOrdinal(column)))
         result = (T)reader.GetValue(reader.GetOrdinal(column));

     return result;
 }

How is this written in VB.NET? How does the method signature change when returning a generic type?

Upvotes: 4

Views: 9145

Answers (2)

Matt
Matt

Reputation: 14531

You can use the C# to VB.NET converter which produces the following results:

Public Function ParseValue(Of T)(reader As System.Data.SqlClient.SqlDataReader, column As String) As T
    Dim result As T = Nothing

    If Not reader.IsDBNull(reader.GetOrdinal(column)) Then
        result = DirectCast(reader.GetValue(reader.GetOrdinal(column)), T)
    End If

    Return result
End Function

Additionally:

I would recommend the following resource to help know syntax differences between VB.NET and C#. It has a section on Generics:

VB.NET and C# Comparison

Upvotes: 7

user541686
user541686

Reputation: 210445

Public Function ParseValue(Of T)(reader As System.Data.SqlClient.SqlDataReader, _
                                     column As String) As T
    Dim result As T = Nothing

    If Not reader.IsDBNull(reader.GetOrdinal(column)) Then
        result = DirectCast(reader.GetValue(reader.GetOrdinal(column)), T)
    End If

    Return result
End Function

From C# to VB.NET converter.

Upvotes: 2

Related Questions