473,668 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

step through a struct using foreach

Can I step through a struct using foreach? I want a method that steps
through a struct, and prints out the name/value of each member. Can
it be done?

The error I get when trying this is: "foreach statement cannot
operate on variables of type '...' because '...' does not contain a
public definition for 'GetEnumerator' . And it points me to
http://msdn2.microsoft.com/en-us/lib...eb(vs.80).aspx

I guess this is the answer, but it is over my head at this moment.

Apr 30 '07 #1
6 13181
What do you mean, "steps through a struct"? If you mean the
sub-properties, then something like

foreach(Propert yDescriptor property in
TypeDescriptor. GetProperties(m yValue)) {
Debug.WriteLine (property.GetVa lue(myValue),
property.Name);
}

may suffice...

Marc
Apr 30 '07 #2
Marc,

Here's example code (that does not work) of what I was trying to do:

namespace DisplayStructCo ntentsTest
{
class Program
{

struct Employee
{
public string name;
public int age;
public string location;
};

static void Main(string[] args)
{
Employee employee;

employee.name = "Jim Smith";
employee.age = 35;
employee.locati on = "California ";

foreach (object obj in employee)
{
Console.WriteLi ne(obj + " = " + obj.ToString()) ;

// Output I wish for:
//
// name = Jim Smith
// age = 35
// location = California
}
}
}
}

May 1 '07 #3
The point is, if I modify the struct, I want the code to automatically
handle the new structure. For example, if I add a "birthdate" field,
the code should (without modification) display the birthdate.

May 1 '07 #4
Exposing fields forces you to use reflection; very similar to the
component model code:

foreach (FieldInfo fi in employee.GetTyp e().GetFields() ) {
Console.WriteLi ne(fi.Name + " = " +
Convert.ToStrin g(fi.GetValue(e mployee)));
}

But!! I can't tell you how to code, but you are a: using public
fields, and b: using mutable structs. Neither of these is particularly
good practice in .Net. Please note that CLR structs are very different
to C[++] structs; they are not the same, and perhaps it was
unfortunate to call them structs in C#. What you have feels more like
a class. The public fields are marginally less critical, but prevent
you from doing any find of validation / notification, or changing the
model. I strongly advise using .Net the way it is intended, i.e.
(short version):

class Employee {
private string name, location;
private int age;
public string Name { get { return name; } set { name =
value; } }
public string Location { get { return location; } set {
location = value; } }
public int Age { get { return age; } set { age =
value; } }
};

This obeys a lot more CLR conventions, and will work more as expected
in collections etc.

Marc
May 1 '07 #5
Don't worry... we get it ;-p See other post.

However; this precisely illustrates my point re properties. When you
add the "birthdate" , you might want to cease having "age" as a field,
and start using a calculated "get", i.e. using the offset from
DateTime.Now when the "get" is called.

Marc
May 1 '07 #6
titan nyquist wrote:
The point is, if I modify the struct, I want the code to automatically
handle the new structure. For example, if I add a "birthdate" field,
the code should (without modification) display the birthdate.
The following should do it:

Employee employee;

employee.name = "Jim Smith";
employee.age = 35;
employee.locati on = "California ";

Type t = employee.GetTyp e();
System.Reflecti on.FieldInfo [] fields =
t.GetFields(Sys tem.Reflection. BindingFlags.In stance|System.R eflection.Bindi ngFlags.Public) ;

foreach (System.Reflect ion.FieldInfo field in fields)
{
Console.WriteLi ne(field.Name + " = " + field.GetValue( employee));
}
--
Tom Porterfield
May 1 '07 #7

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

Similar topics

3
28698
by: Filippo P. | last post by:
Hi there, I have a menu (Collection) that needs to be trimmed based on security access of the logged user. protected void AdjustMenuBasedOnUserSecurity(Items ItemsList) { foreach (Item i in ItemsList) {
16
2240
by: Islam Elkhayat | last post by:
In my web application i use satalite assembly to localize my web form.. Instead of set the each control text to the resourcemanager getstring() method i try to use foreach loop private string rmg(string key) { return resource.GetString("key"); } private Literal ctrl_txt()
1
4580
by: caldera | last post by:
Hi, I want to find the web user control in the datalist. I iterate the datalist using foreach statement in the DataListItem and in thi DataListItem I iterate all Controls objects but I can't find web user control, but I found that it is in the namedcontrols. How can I find the web user control using foreach in the datalist Thanks.
5
2272
by: Johannes Röckert | last post by:
Hi, can anyone help me on how to develop a program in c++ which does single step execution using a callback between the asm commands? I need something like debuggers do - a callback function should be called after each command. I think the resulting code could be fairly small and look somehow like this: static int numCommands = 0; // Var which stores the number of commands
1
4332
khalidbaloch
by: khalidbaloch | last post by:
hi every one, how are you folf , hope fine dear Friends i want to get values of multi-dimensional arrays using foreach loop and after that print out the html using an other while loop , i tried alot but did not successed accutly i want to create an yahoo api websearch application i got a sample from developer.yahoo.com for this purpose ,this sample uses unserialize/serialize php here is the code exapmle <?php // Parsing Yahoo! REST...
3
33360
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current code is here: foreach ( string propertyName in ht.Keys ) { this.setProperty( propertyName, ht );
1
1558
by: vit159 | last post by:
I have Data Recive it from stordProceder and i want to Get this data using foreach loop to equal it with local variable
1
3433
by: Doug | last post by:
Hi, I have a collection of objects and I need to compare each item in the collection to see if it's a match on any or all of the others. I have stored my collection in an item like so: "List<PossibleDupsdups" where PossibleDups is an object of my own creation. I have been looking at how the ForEach and FindAll methods work and here is what I was thinking might be a good approach to doing this (in pseudocode):
2
5209
by: berrylthird | last post by:
This question was inspired by scripting languages such as JavaScript. In JavaScript, I can access members of a class using array syntax as in the following example: var myInstance:myClass = new myClass(); myInstance.member_0 = memberValue_0; // absolute notation myInstance = memberValue_0; // relative notation myInstance = memberValue_0; // nominal notation You can initialize a struct in C/C++ like you would an array, as with the...
0
8462
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
8381
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
8658
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7401
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 project—planning, coding, testing, and deployment—without 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
6209
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
4205
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...
1
2792
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
2026
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1786
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.