Using CType to Cast to Variable Type

C

Charles Law

I have the following lines

Dim t As Type = GetType(MyType)
Dim serialiser As New XmlSerializer(t)

I want to be able to do the following with a FileStream fs

Dim instance As MyType

instance = CType(serialiser.Deserialize(fs), MyType)

but replacing MyType with something more generic, for example

instance = CType(serialiser.Deserialize(fs), t)

Obviously, this does not compile, but could someone tell me what I should
put as the second parameter to CType to make it work? I have tried all
sorts, but just get a selection of compile time errors.

The object of the excercise is to have a shared method of a base class that
deserialises (and serialises) the class.

TIA

Charles
 
R

Ray Cassick

If instance is of type MyType the it only makes sense to use CType to cast
the desterilized stream into MyType as below:

instance = CType(serialiser.Deserialize(fs), MyType)

If you are trying to create a common function to desterilize different types
of objects then you might need to look into the object type.
 
R

Ray Cassick

Sorry.. hit send too soon there.. as I was saying...

Deserialize to object in the shared function thern cast afterwards once you
know the type.

Dim instance As Object

instance = CType(serialiser.Deserialize(fs), Object)

.. . .

Dim var As MyType

var = DirectCast(instance, MyType)

Thsi moves the actual casting code into the code that really knows what the
MyType IS. You can catch an InvaklidCast Exception if soemeone tries to cast
to a type that is different...

Or, you can maybe try setitng up your shared function to take a string name
of the type you want to deserialze and use that..
 
C

Charles Law

Hi Ray

Thanks for the suggestions. I think I may have come up with a satisfactory
way to do it. It requires a bit of code in each inheriting class, but also
works if the function is not shadowed.

<code>
Public MustInherit Class MyTypeBase

Public Function Deserialise() As Object

Return New Object

End Function

End Class

Public Class MyType

Inherits MyTypeBase

Public Shadows Function Deserialise() As MyType

Return DirectCast(MyBase.Deserialise, MyType)

End Function

End Class
</code>

Charles
 

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