BinaryWriter - Dynamic cast

J

jfbaro

Hi,

I am new to C# and I don't know how to cast dynamically an object to a
specific type . I have the object and its type (as a Type object).

For example, I read some data from a query (which has been created
dynamically) and get a list of objects and theirs types (string, Int64,
DateTime...). Now I need to put them into a BinaryWrite. Is there any
way of dynamically define which Write method to call?? I don't want to
have a BIG switch to test each possible Type.

I would like to have something similar to that:

Object obj = new Object(); \\ it comes from a datareader... let's
assume it is a string
objBinaryWriter.Write(obj as obj.GetType());

Thanks in advance
 
N

Nicholas Paldino [.NET/C# MVP]

You can't do this. You would have to check the type and have a big
switch statement.

Or, if you want, and don't mind the performance hit, you could use
reflection. Get the type for BinaryWriter and find the method which takes
one parameter of the type of obj.GetType, then call that method, passing in
your object.

Hope this helps.
 

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