473,379 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Reading a struct, field by field

Is there a way to read a struct field by field?

I want to write a rather general function, like:

public string EncodeStruct (struct strct)
{
....
}

which accepts a general struct type, reads it field by field, encodes
each field depending on its type (i.e. an integer field is encoding is
different than a boolean), concatenates the results into a string and
returns it.

Jan 26 '06 #1
12 3545
Sadeq wrote:
Is there a way to read a struct field by field?

I want to write a rather general function, like:

public string EncodeStruct (struct strct)
{
...
}

which accepts a general struct type, reads it field by field, encodes
each field depending on its type (i.e. an integer field is encoding is
different than a boolean), concatenates the results into a string and
returns it.


Have a look at Type.GetFields.

Note that you can't have a method signature like the one you've got at
the moment. If you're using .NET 2.0, you can do something like:

public string EncodeStruct<T> (T value) where T : struct
{
Type type = typeof(T);
...
}

If you're using 1.1, you'll probably need to take the hit of boxing the
value and make the signature of the method just EncodeStruct(object
value).

Jon

Jan 26 '06 #2
Jon Skeet [C# MVP] wrote:

<snip>
Note that you can't have a method signature like the one you've got at
the moment. If you're using .NET 2.0, you can do something like:

public string EncodeStruct<T> (T value) where T : struct
{
Type type = typeof(T);
...
}

If you're using 1.1, you'll probably need to take the hit of boxing the
value and make the signature of the method just EncodeStruct(object
value).


Actually, thinking about it further, you'll have to take the hit of
boxing at least once anyway, as FieldInfo.GetValue takes object as a
parameter.

Jon

Jan 26 '06 #3
Thanks a lot. That was of great help.

I used .NET 2.0 syntax, and now I'm able to implement my own encoder.

But another issue arose when I wanted to encode nested structs. I tried
to use it recursively, but I the compiler cannot cast the obtained
field (which is an object, in general) to a struct.

Is there a way to overcome this issue?

Jan 26 '06 #4
Sadeq <MS******@gmail.com> wrote:
Thanks a lot. That was of great help.

I used .NET 2.0 syntax, and now I'm able to implement my own encoder.

But another issue arose when I wanted to encode nested structs. I tried
to use it recursively, but I the compiler cannot cast the obtained
field (which is an object, in general) to a struct.

Is there a way to overcome this issue?


Well, why not just use it in its boxed form? As I said elsewhere, I
don't think you'll be able to get round it being boxed at some stage
anyway - you might as well take the hit once and be done with it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 26 '06 #5
So, there's no way to unbox an object (a boxed struct) back to the
struct?

And another thing: Is there a way to know if an object is in fact a
boxed struct?

Jan 26 '06 #6
Why not just use binaryserializer? Serialize to byte[], then return base64
string of that?

--
William Stacey [MVP]

"Sadeq" <MS******@gmail.com> wrote in message
news:11*********************@g44g2000cwa.googlegro ups.com...
| Is there a way to read a struct field by field?
|
| I want to write a rather general function, like:
|
| public string EncodeStruct (struct strct)
| {
| ...
| }
|
| which accepts a general struct type, reads it field by field, encodes
| each field depending on its type (i.e. an integer field is encoding is
| different than a boolean), concatenates the results into a string and
| returns it.
|
Jan 27 '06 #7
Sadeq <MS******@gmail.com> wrote:
So, there's no way to unbox an object (a boxed struct) back to the
struct?
Yes - just cast it.
And another thing: Is there a way to know if an object is in fact a
boxed struct?


You can call GetType(), and then use IsValueType() on the returned
Type.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 27 '06 #8
Hi
Sorry, I was busy with a project, so I checked the answers a bit late
;) And b4 everything, thanx 4 ur answers.

I think I should clarify my problem a bit more: I want to write a
general function, which takes a struct (any type which is of type
struct is acceptable) and encodes into a string. This encoding is a
special, so I connot use .NET Serializiation.

First of all, with Jon Skeet's help, I wrote the function as follows:

public String encodeStruct<T>(T sequence) where T:struct
{
Type type;
StringBuilder sb = new StringBuilder();
FieldInfo[] fields = sequence.GetType().GetFields();
foreach (FieldInfo f in fields)
{
type = f.FieldType;
if (type == typeof(int))
sb.Append(encodeInteger((int)f.GetValue(sequence)) );
else if (type == typeof(DateTime))
sb.Append(encodeUTCTime((DateTime)f.GetValue(seque nce)));
else if (type == typeof(Boolean))
sb.Append(encodeBoolean((Boolean)f.GetValue(sequen ce)));
Jan 29 '06 #9

"Sadeq" <MS******@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Hi
Sorry, I was busy with a project, so I checked the answers a bit late
;) And b4 everything, thanx 4 ur answers.

I think I should clarify my problem a bit more: I want to write a
general function, which takes a struct (any type which is of type
struct is acceptable) and encodes into a string. This encoding is a
special, so I connot use .NET Serializiation.

First of all, with Jon Skeet's help, I wrote the function as follows:

public String encodeStruct<T>(T sequence) where T:struct
{
Type type;
StringBuilder sb = new StringBuilder();
FieldInfo[] fields = sequence.GetType().GetFields();
foreach (FieldInfo f in fields)
{
type = f.FieldType;
if (type == typeof(int))
sb.Append(encodeInteger((int)f.GetValue(sequence)) );
else if (type == typeof(DateTime))
sb.Append(encodeUTCTime((DateTime)f.GetValue(seque nce)));
else if (type == typeof(Boolean))
sb.Append(encodeBoolean((Boolean)f.GetValue(sequen ce)));
.
.
.
.
.
}
return sb.ToString();
}

You see, I implemented my own encoders for many types, like Integer,
DateTime, Boolean, etc.

Everything was good till I encountered a case in which I should encode
nested structs, i.e. there was a struct within another one. Note that
the inner struct can be general too, so I did't know in advance what
kind of struct I should cast it to. First I tried something like this
(Calling encodeStruct recursively):

if(type == typeof(struct))
sb.Append(encodeStruct((struct)f.GetValue(sequence )));

But it doesn't work for 2 reasons:
1- typeof(struct) returns error.
2- cast to "struct" returns error.

I solved the first issue using "IsValueType()" function, Thanx to Jon
Skeet.

To solve the second issue, I changed the function signature so that it
accepts an object instead of the generic T, and there was no problem.
But I was wondering if I can cast a general boxed struct [in this case,
f.GetValue(sequence)] to a struct so that I don't have to lose this
good feature of .NET 2.0, namely generics (You know, they apply
compile-time type checking, have better performance, etc).


There are two ways to go here:

1) Semi-generic: Use a generic wrapper to ensure that it is only called from
USER code for structs. Have this wrapper call an internal, non-generic,
object version (which is recursive).

2) The XmlSerializer approach: construct a fully typesafe generic serializer
dynamically.

option 2 doesn't really buy you anything apart from efficiency because the
serializer creation method is trying to do much the same sort of operation
as the encodeStruct method.

In short - generics and reflection can never be mixed in the way you want
because using reflection necessarily means that you haven't got the compile
time types that are needed for generics.

P.S. Just thought of optuion 3: call encodeStruct<T> dynamically. It would
work but what is the point of calling a typesafe method in a non-typesafe
way.

Jan 30 '06 #10
Can you tell me about your first way (Semi-generic) more? I don't have
an idea of how to implement it. Do you mean I should create a generic
class like this:

class sequence<T> { ... }

and use it instead of "struct" type?
Nick Hounsome wrote:
There are two ways to go here:

1) Semi-generic: Use a generic wrapper to ensure that it is only called from
USER code for structs. Have this wrapper call an internal, non-generic,
object version (which is recursive).

2) The XmlSerializer approach: construct a fully typesafe generic serializer
dynamically.

option 2 doesn't really buy you anything apart from efficiency because the
serializer creation method is trying to do much the same sort of operation
as the encodeStruct method.

In short - generics and reflection can never be mixed in the way you want
because using reflection necessarily means that you haven't got the compile
time types that are needed for generics.

P.S. Just thought of optuion 3: call encodeStruct<T> dynamically. It would
work but what is the point of calling a typesafe method in a non-typesafe
way.


Jan 30 '06 #11
Sorry - I didn't really think it through.
I was just thinking:

public String encodeStruct<T>(T sequence) where T:struct
{
return realEncode(sequence);
}

private string realEncode(Object sequence)
{
/* The (recursive) guts of your existing method */
}

But this gives you nothing extra.

I would suggest that you retain the generic because it saves one level of
boxing and enforces that you only call it with a value type - however the
code has to be as if the parameter was always Object (or ValueType) so maybe
just using encodeStruct(ValueType sequence) is the cleanest method.

The fact remains that generics and reflection don't really mix well and the
reasons relate to the concepts themselves rather than the language.
"Sadeq" <MS******@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
Can you tell me about your first way (Semi-generic) more? I don't have
an idea of how to implement it. Do you mean I should create a generic
class like this:

class sequence<T> { ... }

and use it instead of "struct" type?
Nick Hounsome wrote:
There are two ways to go here:

1) Semi-generic: Use a generic wrapper to ensure that it is only called
from
USER code for structs. Have this wrapper call an internal, non-generic,
object version (which is recursive).

2) The XmlSerializer approach: construct a fully typesafe generic
serializer
dynamically.

option 2 doesn't really buy you anything apart from efficiency because
the
serializer creation method is trying to do much the same sort of
operation
as the encodeStruct method.

In short - generics and reflection can never be mixed in the way you want
because using reflection necessarily means that you haven't got the
compile
time types that are needed for generics.

P.S. Just thought of optuion 3: call encodeStruct<T> dynamically. It
would
work but what is the point of calling a typesafe method in a non-typesafe
way.

Jan 30 '06 #12
Thanx. I think this semi-grneric is better than no generics at all.

Of course the reflection and generics concepts do not mix well, but if
microsoft invented a way to "JUST" let the users cast to a general
"struct", there were no problems. I think this can be done without
mixing compile time and runtime concepts. Don't u think so?

Jan 30 '06 #13

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

Similar topics

6
by: Dietrich Epp | last post by:
Are there any good modules for reading a bitstream? Specifically, I have a string and I want to be able to get the next N bits as an integer. Right now I'm using struct.unpack and bit operations,...
3
by: muser | last post by:
With the following code I'm trying to read a text file (infile) and output inaccuracies to the error file (printerfile). The text file is written and stored on disk, while the printerfile has to be...
1
by: muser | last post by:
The following program reads two lines of a file in my A drive and reads no more. Can some sarmartian tell me why that is. Please copy and paste the program into your own compiler please. ...
6
by: The_Kingpin | last post by:
Hi again guys, I've decided to cut my project in section and I found it way easier like this. I'm having a little problem reading struct in a file though. I think after this I'll be able to...
4
by: Henk | last post by:
Hi, I am new to the c-programming language and at the moment I am struggling with the following: I want to read a file using fread() and then put it in to memory. I want to use a (singel)...
1
by: Alex | last post by:
I have a simple enough struct.. public struct InstallationGeneral_Lock { public int Case_name; public int Run_year; public int Inst_name; public int Inst_loc; public int State; public int...
16
by: Jm.GlezdeRueda | last post by:
Hi all, Im trying to read a 24bit bmp with fread, and i have some problems.. I want to read the whole structure in one time, but i dont know why, it only reads the first member well.. I have...
21
by: Stephen.Schoenberger | last post by:
Hello, My C is a bit rusty (.NET programmer normally but need to do this in C) and I need to read in a text file that is setup as a table. The general form of the file is 00000000 USNIST00Z...
6
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.