Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. :)

like image 345
Brian MacKay Avatar asked Dec 10 '25 20:12

Brian MacKay


1 Answers

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
like image 132
aligray Avatar answered Dec 12 '25 10:12

aligray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!