How to use a Generic's base type?

A

Arthur Dent

Hi all... Heres what im looking to do.... I have a Generic class i wrote.
Now, on another class, i want to add a method which can take in an object of
my generic class...
but the catch is, i want it to be able to take in an instance of the generic
REGARDLESS of what the "Of"
type of the generic is.

E.g. .... given a generic class MyGen(Of T)

I want to be able to write another class as such:

Class MyOther
.....
Public Sub DoIt(myarg As MyGen)
... do something ...
End Sub
.....
End Class

The editor/compiler complains though that i did not specify an "Of" on the
argument myarg.
But that is specifically what i want to do, is make a method which just
takes a MyGen instance,
regardless of its "Of"

Can i do this?

Thanks in advance,
- Arthur Dent.
 
J

Jay B. Harlow [MVP - Outlook]

Arthur,
| but the catch is, i want it to be able to take in an instance of the
generic
| REGARDLESS of what the "Of"
| type of the generic is.
Have you tried to define DoIt as a generic Method?

Something like:

| Class MyOther
| .....
| Public Sub DoIt(Of T) (myarg As MyGen(Of T))
| ... do something ...
| End Sub
| .....
| End Class

Because of "type inference" you can just call DoIt with an instance of the
generic, without specifically specifying T, and the compiler will "infer T".

Dim a As New MyGen(Of Integer)
Dim b As New MyGen(Of String)

Dim other As New MyOther

other.DoIt(a)
other.DoIt(b)

If you like you can specify the T parameter:

other.DoIt(Of Integer)(a)
other.DoIt(Of String)(b)

However there is no real benefit to specifying the type, as long as VB can
infer the type. If VB cannot infer the type based on the parameters, then
you need to give the type.


--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


| Hi all... Heres what im looking to do.... I have a Generic class i wrote.
| Now, on another class, i want to add a method which can take in an object
of
| my generic class...
| but the catch is, i want it to be able to take in an instance of the
generic
| REGARDLESS of what the "Of"
| type of the generic is.
|
| E.g. .... given a generic class MyGen(Of T)
|
| I want to be able to write another class as such:
|
| Class MyOther
| .....
| Public Sub DoIt(myarg As MyGen)
| ... do something ...
| End Sub
| .....
| End Class
|
| The editor/compiler complains though that i did not specify an "Of" on the
| argument myarg.
| But that is specifically what i want to do, is make a method which just
| takes a MyGen instance,
| regardless of its "Of"
|
| Can i do this?
|
| Thanks in advance,
| - Arthur Dent.
|
|
 

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