473,767 Members | 2,131 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How To Obtain Type for Generic Conversion

I want to do something like this:

obj = CType(value, Value.Type)

Well, not exactly, but I think that captures the essence. I realise it won't
work as I have written it, and it looks a bit like a nebulous statement, but
I am looking for a generic way to convert a variable of unknown type to its
actual type.

Perhaps a better example would be

Enum MyEnum As Byte
AnElement
AnotherElement
End Enum

Dim e As MyEnum
Dim obj as Object

e = AnotherElement

obj = CType(e, Byte)

The thing is, I don't know, until runtime what the underlying type is.

Any thoughts?

TIA

Charles
Nov 20 '05 #1
6 5184
Hi Charles,

Can you not do something with overloaded functions: That much types are not
there and maybe even less when you know what you use.

function charles(byval item as integer) as integer
end function

function charles(byval item as string) as string
end function

I did not try it, just something that came up and maybe it helps you.

Cor

Nov 20 '05 #2
Hi Cor

I think, from what you are suggesting, that the compiler would have to know
at compile time what the type was, so that it could use the correct
overloaded function. In fact, the type won't be known until runtime.

What I am actually doing, is using reflection to translate a structure into
a byte array. As I iterate through the structure - which I am passed at
runtime - each element may have a different type, and I wish to convert each
type into the correct number of bytes for its internal storage.

Charles
"Cor Ligthert" <no**********@p lanet.nl> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
Hi Charles,

Can you not do something with overloaded functions: That much types are not there and maybe even less when you know what you use.

function charles(byval item as integer) as integer
end function

function charles(byval item as string) as string
end function

I did not try it, just something that came up and maybe it helps you.

Cor

Nov 20 '05 #3
Charles,
Have you tried:

Dim e As MyEnum = MyEnum.AnotherE lement
Dim obj as Object

Dim theType As Type = GetType(Byte)

obj = Convert.ChangeT ype(value, theType)

Hope this helps
Jay

"Charles Law" <bl***@nowhere. com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I want to do something like this:

obj = CType(value, Value.Type)

Well, not exactly, but I think that captures the essence. I realise it won't work as I have written it, and it looks a bit like a nebulous statement, but I am looking for a generic way to convert a variable of unknown type to its actual type.

Perhaps a better example would be

Enum MyEnum As Byte
AnElement
AnotherElement
End Enum

Dim e As MyEnum
Dim obj as Object

e = AnotherElement

obj = CType(e, Byte)

The thing is, I don't know, until runtime what the underlying type is.

Any thoughts?

TIA

Charles

Nov 20 '05 #4
Hi Jay

Thanks. I have tried it now, but it seems to work only for byte types.
Anything larger throws an exception "Value was either too large or too small
for an unsigned byte".

The code I currently have is below:

<code>
Public Shared Function ToByteArray(ByV al MyStruct As Object) As Byte()

' Convert a structure into a byte array

Dim al As ArrayList

Dim Fields As FieldInfo()

Try
Fields = MyStruct.GetTyp e.GetFields

al = New ArrayList

For Each fld As FieldInfo In Fields
If fld.FieldType.E quals(GetType(B yte)) Then
' Add byte to array list
al.Add(CByte(fl d.GetValue(MySt ruct)))

ElseIf fld.FieldType.E quals(GetType(I nt16)) Then
' Add 16-bit value to array list
Dim i16 As Int16

i16 = CType(fld.GetVa lue(MyStruct), Int16)

' Little-endian
al.Add(CByte(i1 6 And &HFF))
al.Add(CByte((i 16 And &HFF00) >> 8))

' Big-endian
'al.Add(CByte(i 16 >> 8))
'al.Add(CByte(i 16 And &HFF))

ElseIf fld.FieldType.E quals(GetType(S omeEnumeratedVa lue))
Then
' This is coded as a byte
al.Add(CByte(fl d.GetValue(MySt ruct)))

ElseIf fld.FieldType.E quals(GetType(S omethingElse)) Then
' This is coded as a byte
al.Add(CByte(fl d.GetValue(MySt ruct)))

Else
Throw New Exception("Cann ot convert type " &
fld.FieldType.T oString)
End If
Next fld

Catch ex As Exception
Throw

End Try

Return DirectCast(al.T oArray(GetType( Byte)), Byte())

End Function
</code>

As you will see, there is the potential for a lot of If .. Then ... Elses. I
am looking for a generic way to convert to save all the typing and
duplication. Any thoughts?

Charles
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:OJ******** *****@TK2MSFTNG P11.phx.gbl...
Charles,
Have you tried:

Dim e As MyEnum = MyEnum.AnotherE lement
Dim obj as Object

Dim theType As Type = GetType(Byte)

obj = Convert.ChangeT ype(value, theType)

Hope this helps
Jay

"Charles Law" <bl***@nowhere. com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I want to do something like this:

obj = CType(value, Value.Type)

Well, not exactly, but I think that captures the essence. I realise it

won't
work as I have written it, and it looks a bit like a nebulous statement,

but
I am looking for a generic way to convert a variable of unknown type to

its
actual type.

Perhaps a better example would be

Enum MyEnum As Byte
AnElement
AnotherElement
End Enum

Dim e As MyEnum
Dim obj as Object

e = AnotherElement

obj = CType(e, Byte)

The thing is, I don't know, until runtime what the underlying type is.

Any thoughts?

TIA

Charles


Nov 20 '05 #5
Charles,
Thanks. I have tried it now, but it seems to work only for byte types.
Anything larger throws an exception "Value was either too large or too small for an unsigned byte".
The code I gave IS for byte types! Notice the GetType(Byte) in there, you
would need to change GetType(Byte) to the specific type you are interested
in (for example FieldInfo.Field Type). Remember an Enum can be Byte, Short,
Integer or Long.
Dim theType As Type = GetType(Byte) ' convert to byte Dim theType As Type = GetType(Integer ) ' convert to integer
Dim theType As Type = GetType(String) ' convert to string
Dim theType As Type = GetType(Double) ' convert to double obj = Convert.ChangeT ype(value, theType)
Unfortunately it does not really make sense to convert an integer to an
integer, as I don't see that really buys you anything!

What are you really attempting to do???

Have you looked at BinarySerializa tion?
I would use a MemoryStream & BinaryWriter if I really needed to implement
the ToByteArray routine. Something like:

' Convert a structure into a byte array
Public Shared Function ToByteArray(ByV al MyStruct As Object) As Byte()
Dim stream As New MemoryStream
Dim writer As New BinaryWriter(st ream)
Dim fields() As FieldInfo = MyStruct.GetTyp e().GetFields()
For Each fld As FieldInfo In fields
If fld.FieldType Is GetType(Byte) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), Byte))
ElseIf fld.FieldType Is GetType(Short) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), Short))
ElseIf fld.FieldType Is GetType(Integer ) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), Integer))
ElseIf fld.FieldType Is GetType(String) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), String))
ElseIf fld.FieldType.I sEnum Then
' find the underlying type of enum and write that.
Else
' get all the fields on the Structure or Class fields
writer.Write(To ByteArray(fld.G etValue(MyStruc t)))
End If
Next fld

Return stream.GetBuffe r()
End Function

Alternatively you can use BitConverter.Ge tBytes to get an array of bytes
given a value.

Note both BinaryWriter & GetBytes don't allow you to work with an object
variable directly.

Hope this helps
Jay
"Charles Law" <bl***@nowhere. com> wrote in message
news:OZ******** ******@TK2MSFTN GP11.phx.gbl... Hi Jay

Thanks. I have tried it now, but it seems to work only for byte types.
Anything larger throws an exception "Value was either too large or too small for an unsigned byte".

The code I currently have is below:

<code>
Public Shared Function ToByteArray(ByV al MyStruct As Object) As Byte()

' Convert a structure into a byte array

Dim al As ArrayList

Dim Fields As FieldInfo()

Try
Fields = MyStruct.GetTyp e.GetFields

al = New ArrayList

For Each fld As FieldInfo In Fields
If fld.FieldType.E quals(GetType(B yte)) Then
' Add byte to array list
al.Add(CByte(fl d.GetValue(MySt ruct)))

ElseIf fld.FieldType.E quals(GetType(I nt16)) Then
' Add 16-bit value to array list
Dim i16 As Int16

i16 = CType(fld.GetVa lue(MyStruct), Int16)

' Little-endian
al.Add(CByte(i1 6 And &HFF))
al.Add(CByte((i 16 And &HFF00) >> 8))

' Big-endian
'al.Add(CByte(i 16 >> 8))
'al.Add(CByte(i 16 And &HFF))

ElseIf fld.FieldType.E quals(GetType(S omeEnumeratedVa lue))
Then
' This is coded as a byte
al.Add(CByte(fl d.GetValue(MySt ruct)))

ElseIf fld.FieldType.E quals(GetType(S omethingElse)) Then
' This is coded as a byte
al.Add(CByte(fl d.GetValue(MySt ruct)))

Else
Throw New Exception("Cann ot convert type " &
fld.FieldType.T oString)
End If
Next fld

Catch ex As Exception
Throw

End Try

Return DirectCast(al.T oArray(GetType( Byte)), Byte())

End Function
</code>

As you will see, there is the potential for a lot of If .. Then ... Elses. I am looking for a generic way to convert to save all the typing and
duplication. Any thoughts?

Charles
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:OJ******** *****@TK2MSFTNG P11.phx.gbl...
Charles,
Have you tried:

Dim e As MyEnum = MyEnum.AnotherE lement
Dim obj as Object

Dim theType As Type = GetType(Byte)

obj = Convert.ChangeT ype(value, theType)

Hope this helps
Jay

"Charles Law" <bl***@nowhere. com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I want to do something like this:

obj = CType(value, Value.Type)

Well, not exactly, but I think that captures the essence. I realise it

won't
work as I have written it, and it looks a bit like a nebulous

statement, but
I am looking for a generic way to convert a variable of unknown type
to its
actual type.

Perhaps a better example would be

Enum MyEnum As Byte
AnElement
AnotherElement
End Enum

Dim e As MyEnum
Dim obj as Object

e = AnotherElement

obj = CType(e, Byte)

The thing is, I don't know, until runtime what the underlying type is.

Any thoughts?

TIA

Charles



Nov 20 '05 #6
Hi Jay

I have several structures that represent message packets. I want to be able
to take any one of these structures and convert it into a byte array so I
can send it down the line. Thus, I would have a single routine that could
take any of these structures and send it.

I don't want to have a series of If.... Thens because the structure could
contain a more complex type. I am only interested in the byte-by-byte
representation of the data in the structure. It is perhaps complicated by
the fact that multi-byte types need to be sent little-endian.

Charles
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:uB******** ******@TK2MSFTN GP12.phx.gbl...
Charles,
Thanks. I have tried it now, but it seems to work only for byte types.
Anything larger throws an exception "Value was either too large or too small
for an unsigned byte".


The code I gave IS for byte types! Notice the GetType(Byte) in there, you
would need to change GetType(Byte) to the specific type you are interested
in (for example FieldInfo.Field Type). Remember an Enum can be Byte, Short,
Integer or Long.
Dim theType As Type = GetType(Byte) ' convert to byte Dim theType As Type = GetType(Integer ) ' convert to integer
Dim theType As Type = GetType(String) ' convert to string
Dim theType As Type = GetType(Double) ' convert to double obj = Convert.ChangeT ype(value, theType)
Unfortunately it does not really make sense to convert an integer to an
integer, as I don't see that really buys you anything!

What are you really attempting to do???

Have you looked at BinarySerializa tion?
I would use a MemoryStream & BinaryWriter if I really needed to implement
the ToByteArray routine. Something like:

' Convert a structure into a byte array
Public Shared Function ToByteArray(ByV al MyStruct As Object) As Byte()
Dim stream As New MemoryStream
Dim writer As New BinaryWriter(st ream)
Dim fields() As FieldInfo = MyStruct.GetTyp e().GetFields()
For Each fld As FieldInfo In fields
If fld.FieldType Is GetType(Byte) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), Byte))
ElseIf fld.FieldType Is GetType(Short) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), Short))
ElseIf fld.FieldType Is GetType(Integer ) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), Integer))
ElseIf fld.FieldType Is GetType(String) Then
writer.Write(Di rectCast(fld.Ge tValue(MyStruct ), String))
ElseIf fld.FieldType.I sEnum Then
' find the underlying type of enum and write that.
Else
' get all the fields on the Structure or Class fields
writer.Write(To ByteArray(fld.G etValue(MyStruc t)))
End If
Next fld

Return stream.GetBuffe r()
End Function

Alternatively you can use BitConverter.Ge tBytes to get an array of bytes
given a value.

Note both BinaryWriter & GetBytes don't allow you to work with an object
variable directly.

Hope this helps
Jay
"Charles Law" <bl***@nowhere. com> wrote in message
news:OZ******** ******@TK2MSFTN GP11.phx.gbl...
Hi Jay

Thanks. I have tried it now, but it seems to work only for byte types.
Anything larger throws an exception "Value was either too large or too

small
for an unsigned byte".

The code I currently have is below:

<code>
Public Shared Function ToByteArray(ByV al MyStruct As Object) As Byte()
' Convert a structure into a byte array

Dim al As ArrayList

Dim Fields As FieldInfo()

Try
Fields = MyStruct.GetTyp e.GetFields

al = New ArrayList

For Each fld As FieldInfo In Fields
If fld.FieldType.E quals(GetType(B yte)) Then
' Add byte to array list
al.Add(CByte(fl d.GetValue(MySt ruct)))

ElseIf fld.FieldType.E quals(GetType(I nt16)) Then
' Add 16-bit value to array list
Dim i16 As Int16

i16 = CType(fld.GetVa lue(MyStruct), Int16)

' Little-endian
al.Add(CByte(i1 6 And &HFF))
al.Add(CByte((i 16 And &HFF00) >> 8))

' Big-endian
'al.Add(CByte(i 16 >> 8))
'al.Add(CByte(i 16 And &HFF))

ElseIf fld.FieldType.E quals(GetType(S omeEnumeratedVa lue)) Then
' This is coded as a byte
al.Add(CByte(fl d.GetValue(MySt ruct)))

ElseIf fld.FieldType.E quals(GetType(S omethingElse)) Then
' This is coded as a byte
al.Add(CByte(fl d.GetValue(MySt ruct)))

Else
Throw New Exception("Cann ot convert type " &
fld.FieldType.T oString)
End If
Next fld

Catch ex As Exception
Throw

End Try

Return DirectCast(al.T oArray(GetType( Byte)), Byte())

End Function
</code>

As you will see, there is the potential for a lot of If .. Then ... Elses. I
am looking for a generic way to convert to save all the typing and
duplication. Any thoughts?

Charles
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in

message news:OJ******** *****@TK2MSFTNG P11.phx.gbl...
Charles,
Have you tried:

Dim e As MyEnum = MyEnum.AnotherE lement
Dim obj as Object

Dim theType As Type = GetType(Byte)

obj = Convert.ChangeT ype(value, theType)

Hope this helps
Jay

"Charles Law" <bl***@nowhere. com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
> I want to do something like this:
>
> obj = CType(value, Value.Type)
>
> Well, not exactly, but I think that captures the essence. I realise it won't
> work as I have written it, and it looks a bit like a nebulous

statement, but
> I am looking for a generic way to convert a variable of unknown type to its
> actual type.
>
> Perhaps a better example would be
>
> Enum MyEnum As Byte
> AnElement
> AnotherElement
> End Enum
>
> Dim e As MyEnum
> Dim obj as Object
>
> e = AnotherElement
>
> obj = CType(e, Byte)
>
> The thing is, I don't know, until runtime what the underlying type is. >
> Any thoughts?
>
> TIA
>
> Charles
>
>



Nov 20 '05 #7

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

Similar topics

14
3001
by: tweak | last post by:
I'm struggling with the concept of typecasting when setting up a TCP client. Here's a code snip (modified from W. Richard Stevens Unix Programming book) to demonstrate where I am struggling: int sockfd; struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr));
4
17684
by: Ken Varn | last post by:
I have an unknown numeric Type object passed into a function. I want to run a conversion on a string to convert the string to that Type object and return an object of that type. Is there some way to do a generic cast or conversion on the type? Here is sort of what I want to do: object MyFunc(Type T, String Str) { object o;
11
14347
by: Demorsy | last post by:
I want to convert a string (or object) to a primitive type. But I don't know the type to convert to at run time. For example l have variable (lets say its an int): int unknownType = 0; And a string: string str = "123"; If I knew the type is int I could have used: unknownType = Convert.ToInt32(str); or int.Parse(str) etc.
3
1880
by: pgconnolly | last post by:
/* foreach does implicit type conversion on elements of a params argument or Generic.List. * This is not good. * Examples of evil follow... */ using System; // I love it when C# is strict with me... using System.Collections.Generic;
1
1674
by: Jinsong Liu | last post by:
Hello Group: I am playing with .NET 2.0 Generic. I have a CarsList<T> Generic class, Is it possible that I can control what T could be? I want to ensure the T can only be classes derived from a specific class (lets say Car). I understand that I can create a CarList without using Generic, but when I add a derived class to the list, type conversion will happen, and I will not be able to enforce type at child class level.
4
4944
by: Harold Howe | last post by:
I am running into a situation where the compiler complains that it cannot infer the type parameters of a generic method when one of the function arguments is an anonymous method. Here is a complete code example: //----------------------------- using System; using System.Collections.Generic;
669
26185
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
9
5849
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
8
1330
by: ThunderMusic | last post by:
Hi, We need to serialize (binary) objects containing generic collections. The thing is, when we try to get the objects back (deserialize) with a different instance of the application, we receive an exception stating the constructor of the generic class does not exist. So Is there a way to obtain the resulting classes of the generics we use so we can add them as "normal" code in our app? We can develop our own starting from non-generic...
0
10013
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
9960
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8838
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7383
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
6655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5424
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3930
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
3533
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2807
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.