Search code examples
c#vb.netgenericsdynamicfluent-interface

Return generic of unspecified type


Is it possible to create a function that returns a generic of unspecified type, like this?

Public Function Create(ByVal type As Type) As DeserializationHelper(Of )
    Dim DynamicHelper = GetType(DeserializationHelper(Of )).MakeGenericType(type)

    Return Activator.CreateInstance(DynamicHelper)
End Function

Everything works here except for strongly typing the return value. I could return it as an object, a non-generic interface or a non-generic base class, but I'm trying to make a very succint fluent style API.

I'm trying to create syntax like this:

Dim Loader As New XLoader(parentContainer, Map)
Dim MyCreature As Creature = Loader.Create(GetType(Creature)).From(xml.<Creature>)

...And yes I know there are built-in xml serializers -- I wish they worked for me, but I need more control. ;)

If I moved this part into a different project and wrote it in C# (and then consumed it from a VB.NET project), would C#'s Dynamic keyword help me at all?

Thanks. :)


Solution

  • Not an expert with VB but hopefully this will help:

    Public Function Create(Of TResult)() As DeserializationHelper(Of TResult)
        Return Activator.CreateInstance(Of DeserializationHelper(Of TResult))()
    End Function