Passing a Generic as a Parameter

M

Mike

This seems like something that should be possible, but I am having
trouble setting up a function to accept a generic type as a parameter.

A basic function that shows what I am trying to do:

Public Class BaseRecord(Of T)
Protected _id As Integer
Public ReadOnly Property ID() As Integer
Get
Return _id
End Get
End Property
End Class

Public Class StringRecord
Inherits BaseRecord(Of String)

Private _value As String
Public ReadOnly Property Value() As String
Get
Return _value
End Get
End Property
End Class

Public Class Validation
Public Shared Function ValidateRecord(ByVal record As
BaseRecord(Of Object)) As Boolean
If record.ID < 0 Then
Return False
Else
Return True
End If
End Function
End Class

However, when I try to call the validation function like this:

Dim rec As New StringRecord()
Validation.ValidateRecord(rec)

I get an error stating "Value of type StringRecord cannot be converted
to BaseRecord(Of Object)"

I have tried making the function "Byval record as BaseRecord(Of T)"
but it states that "Type T is not defined"

Is there a way to pass this record as I am attempting or do I need to
completely rethink the way I am wanting to do validation?

Thank you,
Mike
 
J

Jon Skeet [C# MVP]

However, when I try to call the validation function like this:

Dim rec As New StringRecord()
Validation.ValidateRecord(rec)

I get an error stating "Value of type StringRecord cannot be converted
to BaseRecord(Of Object)"

And indeed it can't. It's a BaseRecord(Of String). They're not
compatible types.
I have tried making the function "Byval record as BaseRecord(Of T)"
but it states that "Type T is not defined"

Is there a way to pass this record as I am attempting or do I need to
completely rethink the way I am wanting to do validation?

Make the method generic as well. I'm afraid I don't know the syntax for
that in VB, but in C# you'd write:

public static bool ValidateRecord<T> (BaseRecord<T> record)
{
return record.ID >= 0;
}
 
M

Mike

Make the method generic as well. I'm afraid I don't know the syntax for
that in VB, but in C# you'd write:

public static bool ValidateRecord<T> (BaseRecord<T> record)
{
    return record.ID >= 0;

}

Thanks, that worked perfectly!

For an VB users who may come across this post, the VB equivelant line
is:
Public Shared Function ValidateRecord(Of T)(ByVal record As
BaseRecord(Of T)) As Boolean
(a lengthy statement, but it gets the job done.

Thanks,
Mike Clark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top