views:

243

answers:

5

Question: I want to call a generic function, defined as:

      Public Shared Function DeserializeFromXML(Of T)(Optional ByRef strFileNameAndPath As String = Nothing) As T

Now when I call it, I wanted to do it with any of the variants below:

Dim x As New XMLserialization.cConfiguration
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of x)()
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(GetType(x))()
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of GetType(x))()

But it doesn't work. I find it very annoying and unreadable having to type

    x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of XMLserialization.cConfiguration)()

Is there a way to call a generic function by getting the type from the instance ?

+2  A: 

Only using the methods of the System.Reflection namespace, which really isn't worth it for the effort you're trying to save.

David M
+1  A: 

The type of a generic method is determined at compile time, which is why you can't set it using a variable. This is a key difference between generic programming and type reflection.

John M Gant
+2  A: 

Generics and reflection make very poor friends. However, you can do this via MakeGenericMethod. However, that is going to be hard and ugly.

Since XmlSerializer is based around Type instance - I would reverse things: have the realy code Type based, and call into that from the shallow generic version; example in C#:

public T DeserializeFromXML<T>(string path) {
   return (T)DeserializeFromXML(typeof(T), path);
}
public object DeserializeFromXML(Type type, string path) {
    //TODO: real code
}
Marc Gravell
+2  A: 

It sounds to me like you want to create a shorter alias for your XMLserialization.cConfiguration type. Try using the Imports statement to accomplish this:

' at the top of the file '
Imports C = XMLserialization.cConfiguration

' somewhere in the body of the file '
Dim x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of C)()
Dan Tao
A: 

[This is answering the question as asked, not necessarily solving your bigger issue.]

To avoid the Of cConfiguration being required you could include an ignored ByVal Configuration As T in the generic method.

Then you could say

x = DeserializeFromXML(x)

But @DanTao's answer is probably better than mine unless you find a use for the Configuration parameter.

Mark Hurd