473,657 Members | 2,534 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting byte array to generic type

I'm building a C# interface to an existing messaging system. The
messaging system allows values of several types to be sent/recieved
over the interface.

What I want to do is use a generic class to produce values in the
system. For instance I could create class

MsgGenericValue <UInt16>() which would represent an unsigned value on
the interface.

My issue is converting from byte [] values to the generic type T.

So if I have a class: MsgGenericValue <T>

With a member

T _Value

I want do be able to do something like

if (_Value is Int32) _Value =
BitConverter.To Int32(Bytes, 0);

But it doesn't compile - It can't convert from Int32 to 'T'

So how do I do this? Any thoughts would be greatly appreciated

Tom

Jan 23 '07 #1
5 9604
Hi Tom,

Having to check "_Value is Int32" is an indication that you shouldn't use
generics here. You should just have a regular property of type Object,
which will allow assignment from any type.

--
Dave Sexton
http://davesexton.com/blog
http://www.codeplex.com/DocProject (Sandcastle in VS IDE)

<vt******@gmail .comwrote in message
news:11******** **************@ a75g2000cwd.goo glegroups.com.. .
I'm building a C# interface to an existing messaging system. The
messaging system allows values of several types to be sent/recieved
over the interface.

What I want to do is use a generic class to produce values in the
system. For instance I could create class

MsgGenericValue <UInt16>() which would represent an unsigned value on
the interface.

My issue is converting from byte [] values to the generic type T.

So if I have a class: MsgGenericValue <T>

With a member

T _Value

I want do be able to do something like

if (_Value is Int32) _Value =
BitConverter.To Int32(Bytes, 0);

But it doesn't compile - It can't convert from Int32 to 'T'

So how do I do this? Any thoughts would be greatly appreciated

Tom

Jan 23 '07 #2
You're absolutely right, Dave.

However, if I do that, then I either have to:
- Write a bunch of specific classes for each type I want to support
or
- Always cast the return value from functions within the class

And I want to avoid that. I do have one way to do it - if I use an
object type variable within the routine, I can check the type; i.e.

T _Value;

object Temp = _Value; // temp to avoid casting
issues

if (_Value is Int32) Temp =
BitConverter.To Int32(NewValue, 0);
else if (_Value is Boolean) Temp =
BitConverter.To Boolean(NewValu e, 0);
else if (_Value is Byte) Temp = NewValue[0];
else if (_Value is Double) Temp =
BitConverter.To Double(NewValue , 0);
else if (_Value is String) Temp =
BitConverter.To String(NewValue );
else if (_Value is UInt32) Temp =
BitConverter.To UInt32(NewValue , 0);
else if (_Value is UInt16) Temp =
BitConverter.To UInt16(NewValue , 0);
else throw new InvalidTypeExce ption("Unsuppor ted type
" + _Value.GetType( ).ToString());

_Value = (T)Temp;

Kind of weird, but it works....

Thanks for the reply.

Tom
On Jan 23, 4:06 pm, "Dave Sexton" <dave@jwa[remove.this]online.com>
wrote:
Hi Tom,

Having to check "_Value is Int32" is an indication that you shouldn't use
generics here. You should just have a regular property of type Object,
which will allow assignment from any type.

--
Dave Sextonhttp://davesexton.com/bloghttp://www.codeplex.co m/DocProject(Sand castle in VS IDE)

<vtjum...@gmail .comwrote in messagenews:11* *************** ******@a75g2000 cwd.googlegroup s.com...
I'm building a C# interface to an existing messaging system. The
messaging system allows values of several types to be sent/recieved
over the interface.
What I want to do is use agenericclass to produce values in the
system. For instance I could create class
MsgGenericValue <UInt16>() which would represent an unsigned value on
the interface.
My issue is converting from byte [] values to thegenerictype T.
So if I have a class: MsgGenericValue <T>
With a member
T _Value
I want do be able to do something like
if (_Value is Int32) _Value =
BitConverter.To Int32(Bytes, 0);
But it doesn't compile - It can't convert from Int32 to 'T'
So how do I do this? Any thoughts would be greatly appreciated
Tom
Jan 29 '07 #3
Hi Tom,

Yes, that'll work :)

It's just that you're trading flexibility within the object for flexibility
outside of the object. In other words, externally you won't have to cast
the object, but if you ever need to support another type you'll have to
modify the object itself, meaning recompilation of the entire assembly just
to support another type. That means that assemblies that reference your
assembly may also require recompilation, even though the type is generic.

I don't know the business requirements for your application or how the
object will be used, obviously, but that's certainly something to consider.

--
Dave Sexton
http://davesexton.com/blog
http://www.codeplex.com/DocProject (Sandcastle in VS IDE)

<vt******@gmail .comwrote in message
news:11******** **************@ h3g2000cwc.goog legroups.com...
You're absolutely right, Dave.

However, if I do that, then I either have to:
- Write a bunch of specific classes for each type I want to support
or
- Always cast the return value from functions within the class

And I want to avoid that. I do have one way to do it - if I use an
object type variable within the routine, I can check the type; i.e.

T _Value;

object Temp = _Value; // temp to avoid casting
issues

if (_Value is Int32) Temp =
BitConverter.To Int32(NewValue, 0);
else if (_Value is Boolean) Temp =
BitConverter.To Boolean(NewValu e, 0);
else if (_Value is Byte) Temp = NewValue[0];
else if (_Value is Double) Temp =
BitConverter.To Double(NewValue , 0);
else if (_Value is String) Temp =
BitConverter.To String(NewValue );
else if (_Value is UInt32) Temp =
BitConverter.To UInt32(NewValue , 0);
else if (_Value is UInt16) Temp =
BitConverter.To UInt16(NewValue , 0);
else throw new InvalidTypeExce ption("Unsuppor ted type
" + _Value.GetType( ).ToString());

_Value = (T)Temp;

Kind of weird, but it works....

Thanks for the reply.

Tom
On Jan 23, 4:06 pm, "Dave Sexton" <dave@jwa[remove.this]online.com>
wrote:
>Hi Tom,

Having to check "_Value is Int32" is an indication that you shouldn't use
generics here. You should just have a regular property of type Object,
which will allow assignment from any type.

--
Dave
Sextonhttp://davesexton.com/bloghttp://www.codeplex.co m/DocProject(Sand castle
in VS IDE)

<vtjum...@gmai l.comwrote in
messagenews:11 *************** *******@a75g200 0cwd.googlegrou ps.com...
I'm building a C# interface to an existing messaging system. The
messaging system allows values of several types to be sent/recieved
over the interface.
What I want to do is use agenericclass to produce values in the
system. For instance I could create class
MsgGenericValue <UInt16>() which would represent an unsigned value on
the interface.
My issue is converting from byte [] values to thegenerictype T.
So if I have a class: MsgGenericValue <T>
With a member
T _Value
I want do be able to do something like
if (_Value is Int32) _Value =
BitConverter.To Int32(Bytes, 0);
But it doesn't compile - It can't convert from Int32 to 'T'
So how do I do this? Any thoughts would be greatly appreciated
Tom

Jan 31 '07 #4
Hi,

Actually, the comments in my last post don't apply to your particular
situation since you're using BitConverter, which doesn't accept object - the
original problem :) Even if you used Object instead of a generic argument
you'd still have to implement the type checking as you have done. And
anyway, there is only a limited number of types that you have to check so
it's no big deal.

I should have looked at your code instead of jumping to conclusions.

--
Dave Sexton
http://davesexton.com/blog
http://www.codeplex.com/DocProject (Sandcastle in VS IDE)

<vt******@gmail .comwrote in message
news:11******** **************@ h3g2000cwc.goog legroups.com...
You're absolutely right, Dave.

However, if I do that, then I either have to:
- Write a bunch of specific classes for each type I want to support
or
- Always cast the return value from functions within the class

And I want to avoid that. I do have one way to do it - if I use an
object type variable within the routine, I can check the type; i.e.

T _Value;

object Temp = _Value; // temp to avoid casting
issues

if (_Value is Int32) Temp =
BitConverter.To Int32(NewValue, 0);
else if (_Value is Boolean) Temp =
BitConverter.To Boolean(NewValu e, 0);
else if (_Value is Byte) Temp = NewValue[0];
else if (_Value is Double) Temp =
BitConverter.To Double(NewValue , 0);
else if (_Value is String) Temp =
BitConverter.To String(NewValue );
else if (_Value is UInt32) Temp =
BitConverter.To UInt32(NewValue , 0);
else if (_Value is UInt16) Temp =
BitConverter.To UInt16(NewValue , 0);
else throw new InvalidTypeExce ption("Unsuppor ted type
" + _Value.GetType( ).ToString());

_Value = (T)Temp;

Kind of weird, but it works....

Thanks for the reply.

Tom
On Jan 23, 4:06 pm, "Dave Sexton" <dave@jwa[remove.this]online.com>
wrote:
>Hi Tom,

Having to check "_Value is Int32" is an indication that you shouldn't use
generics here. You should just have a regular property of type Object,
which will allow assignment from any type.

--
Dave
Sextonhttp://davesexton.com/bloghttp://www.codeplex.co m/DocProject(Sand castle
in VS IDE)

<vtjum...@gmai l.comwrote in
messagenews:11 *************** *******@a75g200 0cwd.googlegrou ps.com...
I'm building a C# interface to an existing messaging system. The
messaging system allows values of several types to be sent/recieved
over the interface.
What I want to do is use agenericclass to produce values in the
system. For instance I could create class
MsgGenericValue <UInt16>() which would represent an unsigned value on
the interface.
My issue is converting from byte [] values to thegenerictype T.
So if I have a class: MsgGenericValue <T>
With a member
T _Value
I want do be able to do something like
if (_Value is Int32) _Value =
BitConverter.To Int32(Bytes, 0);
But it doesn't compile - It can't convert from Int32 to 'T'
So how do I do this? Any thoughts would be greatly appreciated
Tom

Jan 31 '07 #5
Thanks again for the reply. I have this working now...

Tom

Feb 1 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
13915
by: matt melton | last post by:
Hi there, I am trying to write a method that accepts an array of any primitive type and will return the same array without copying memory as an array of bytes. ie. I'd like to be able to do something like: char chars = "Hello!"; byte bytes = (byte) chars;
2
2670
by: Govind | last post by:
Hi All, I want to Convert 32 bit integers to byte in right alighed format . For 32 = the usual way is BitConverter.GetBytes(int32)==> xx xx 00 00 , but i want right aligned like 00 00 xx xx.Is there any way. Regards, Govind.
4
16458
by: Joseph Suprenant | last post by:
I have an array of unsigned chars and i would like them converted to an array of ints. What is the best way to do this? Using RedHat 7.3 on an Intel Pentium 4 machine. Having trouble here, hope someone can help Thanks
6
41611
by: Luis Arvayo | last post by:
Hello, I am trying to convert a jpeg image stored in a PictureBox to a byte array in order to later save it to a database, but I get this error : "Generic Error in GDI+". The source code is the following (when clicking in a button): MemoryStream ms = new MemoryStream(); pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //
8
4193
by: moondaddy | last post by:
I need to convert a byte array to a string and pass it as a parameter in a URL and then convert it back to the original byte array. However, its getting scrambled in the conversion. In short, here's the code: ====================================== Dim textConverter As New ASCIIEncoding Dim sParam As String = "This is my cool param" Dim bytParam() As Byte 'load the byte array here...
6
4553
by: Narshe | last post by:
How can I convert a byte into a byte?? You can assign a byte to a byte?, but you obviously can't do that with an array. The way I'm currently doing it is a for loop that just copies the data from a byte to the byte?. There must be an easier/better way.
3
2568
by: Sharon | last post by:
There is an built-in types table for .NET framework type to C# type which are aliases of predefined types in the System namespace (http://msdn2.microsoft.com/en-US/library/ya5y69ds.aspx). How can use access and use this table (by C# code) to convert the alias to the .NET framework type. For example: if I have: string aliasType = "int"; string frameworkType = ???
17
7239
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
1
4832
by: MimiMi | last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for. I think I am using the same type of algorithm, initialization vector (IV), mode, padding, key etc, but I just don't get the two languages to "understand each other", or, in other words, I must be missing out on something crucial. I encrypt a byte array in C# and send over the byte...
0
8420
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.