PC Review


Reply
Thread Tools Rate Thread

BinaryWriter - Dynamic cast

 
 
jfbaro
Guest
Posts: n/a
 
      15th Dec 2006
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

 
Reply With Quote
 
 
 
 
Nicholas Paldino [.NET/C# MVP]
Guest
Posts: n/a
 
      18th Dec 2006
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.


--
- Nicholas Paldino [.NET/C# MVP]
- (E-Mail Removed)


"jfbaro" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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
>



 
Reply With Quote
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
dynamic cast? Jamie McQuay Microsoft C# .NET 9 21st Feb 2008 08:55 PM
Dynamic cast with generics Néstor Sánchez Microsoft C# .NET 3 29th Jan 2007 08:28 PM
Dynamic cast possible? Zark3 Microsoft C# .NET 4 7th May 2006 09:23 AM
How to cast to a dynamic type ? John Microsoft Dot NET Framework 4 13th Jan 2005 10:22 PM
Dynamic cast situation... Ole Hanson Microsoft C# .NET 3 5th Jan 2005 05:19 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 06:47 AM.