473,683 Members | 2,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get array of class variables

Say I have an Object of the following class:

public class SomeClass {
public string var1;
public int var2;
public SomeType var3;
}

Now I want to print all the three vars. Is it possible to get an array
containing these three vars, making something like this possible:

for (int i = 0; i < myArray.Length; i++) {
myPrintFunction (myArray[i]);
}

Or is there no other option then to print each class variable
explicitly, like this:

myPrintFunction (myObject.var1) ;
myPrintFunction (myObject.var2) ;
myPrintFunction (myObject.var3) ;

My guess would be that the Reflection library makes such a thing
possible, but I could not find it there.

Regards,

Daan
Dec 6 '05 #1
9 4922
foreach (object o in SomeClass)
{
myPrintFunction (o);
}

think something like this should work.

Dec 6 '05 #2
You can override the ToString() method so that it prints out information
appropriate to your object. Then you can just call myObject.ToStri ng(), or
are you looking for something more generic?
"Daan" <d_*****@IDONTL IKESPAMhotmail. com> wrote in message
news:dn******** *@netlx020.civ. utwente.nl...
Say I have an Object of the following class:

public class SomeClass {
public string var1;
public int var2;
public SomeType var3;
}

Now I want to print all the three vars. Is it possible to get an array
containing these three vars, making something like this possible:

for (int i = 0; i < myArray.Length; i++) {
myPrintFunction (myArray[i]);
}

Or is there no other option then to print each class variable explicitly,
like this:

myPrintFunction (myObject.var1) ;
myPrintFunction (myObject.var2) ;
myPrintFunction (myObject.var3) ;

My guess would be that the Reflection library makes such a thing possible,
but I could not find it there.

Regards,

Daan

Dec 6 '05 #3
Peter Rilling wrote:
You can override the ToString() method so that it prints out information
appropriate to your object. Then you can just call myObject.ToStri ng(), or
are you looking for something more generic?


Possible, but then I still need to make my own ToString() function,
which is what I wanted to avoid. The point is, I have a very simple
class, but with quite a large number of variables (about 22). So I like
to have an array containing all those variables, so that I can easily
iterate over that array when I want to use the variables.

ViRi's solution does not seem to work, "foreach statement cannot operate
on variables of type 'SMOBY.ServiceO rder'because 'SMOBY.ServiceO rder'
does not contain a public definition for 'GetEnumerator' "

--
Daan
Dec 6 '05 #4
Implement a ToString() overload for "SomeType" and use it.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but you can't make it stink.

"Daan" <d_*****@IDONTL IKESPAMhotmail. com> wrote in message
news:dn******** *@netlx020.civ. utwente.nl...
Say I have an Object of the following class:

public class SomeClass {
public string var1;
public int var2;
public SomeType var3;
}

Now I want to print all the three vars. Is it possible to get an array
containing these three vars, making something like this possible:

for (int i = 0; i < myArray.Length; i++) {
myPrintFunction (myArray[i]);
}

Or is there no other option then to print each class variable explicitly,
like this:

myPrintFunction (myObject.var1) ;
myPrintFunction (myObject.var2) ;
myPrintFunction (myObject.var3) ;

My guess would be that the Reflection library makes such a thing possible,
but I could not find it there.

Regards,

Daan

Dec 6 '05 #5
Daan wrote:
Peter Rilling wrote:
You can override the ToString() method so that it prints out
information appropriate to your object. Then you can just call
myObject.ToStri ng(), or are you looking for something more generic?

Possible, but then I still need to make my own ToString() function,
which is what I wanted to avoid. The point is, I have a very simple
class, but with quite a large number of variables (about 22). So I like
to have an array containing all those variables, so that I can easily
iterate over that array when I want to use the variables.

ViRi's solution does not seem to work, "foreach statement cannot operate
on variables of type 'SMOBY.ServiceO rder'because 'SMOBY.ServiceO rder'
does not contain a public definition for 'GetEnumerator' "


Can you store the variables in the class as an array? That may simplify
the issue. Otherwise override the tostring method, use reflection to
find all the properties of the class and do a loop in there to create
your string.

Chris
Dec 6 '05 #6
I would recommend using a custom ToString() override, as the other posts
suggested.
But since you asked for a reflection solution and said you couldn't
figure it out, I'll give you an example. This is just to show you how to
do it - this isn't the solution I would recommend in most cases (but
maybe it fits for your scenario).
public class SomeClass
{
public string var1 = "theVar1";
public int var2 = 42;
public DateTime var3 = DateTime.Now;

public object[] GetAllVariables AsArray()
{
FieldInfo[] fields =
this.GetType(). GetFields(Bindi ngFlags.Instanc e | BindingFlags.Pu blic |
BindingFlags.De claredOnly);
// Note - use PropertyInfo and GetProperties() if your values are stored
in properties instead of fields
object[] variables = new object[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
variables[i] = fields[i].GetValue(this) ;
}
return variables;
}
}
An example of using the method would be:

class Program
{
static void Main(string[] args)
{
SomeClass sc = new SomeClass();
foreach (object var in sc.GetAllVariab lesAsArray())
{
Console.WriteLi ne(var.ToString ());
}
}
}

Hope this helps.

Joshua Flanagan
http://flimflan.com/blog

Daan wrote:
Say I have an Object of the following class:

public class SomeClass {
public string var1;
public int var2;
public SomeType var3;
}

Now I want to print all the three vars. Is it possible to get an array
containing these three vars, making something like this possible:

for (int i = 0; i < myArray.Length; i++) {
myPrintFunction (myArray[i]);
}

Or is there no other option then to print each class variable
explicitly, like this:

myPrintFunction (myObject.var1) ;
myPrintFunction (myObject.var2) ;
myPrintFunction (myObject.var3) ;

My guess would be that the Reflection library makes such a thing
possible, but I could not find it there.

Regards,

Daan

Dec 6 '05 #7
ViRi <cm******@gmail .com> wrote:
foreach (object o in SomeClass)
{
myPrintFunction (o);
}

think something like this should work.


No, that wouldn't compile - foreach doesn't work on a type name.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 7 '05 #8
Joshua Flanagan wrote:
But since you asked for a reflection solution and said you couldn't
figure it out, I'll give you an example. This is just to show you how to
do it - this isn't the solution I would recommend in most cases (but
maybe it fits for your scenario).

FieldInfo[] fields =
this.GetType(). GetFields(Bindi ngFlags.Instanc e | BindingFlags.Pu blic |
BindingFlags.De claredOnly);
// Note - use PropertyInfo and GetProperties() if your values are stored
in properties instead of fields
object[] variables = new object[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
variables[i] = fields[i].GetValue(this) ;
}
return variables;


Thanks Joshua, this is what I was looking for. But I wonder why you say
you would not recommend this solution, is there any risk or uglyness
about this solution?

Daan
Dec 7 '05 #9
> Thanks Joshua, this is what I was looking for. But I wonder why you say
you would not recommend this solution, is there any risk or uglyness
about this solution?


1) It is slower to evaluate variables through reflection, rather than
referencing the variable directly. It depends on your situation if the
speed difference matters.

2) I would say it is ugly, since reflection is a type of "cheat". It
doesn't use any of the language's built in constructs and concepts. If
you're variables were designed to be used as individual values, then
treat them as individual values. If they are just values in a
colleciton, then use a collection (array) instead of individual
variables. Again, "uglyness" is in the eye of the beholder - if it
doesn't bother you, go for it.

3) Note that in my solution, you do not know in what order the variable
values will come back in. Do not assume that they will always return in
the same order - you will have to do your own sorting if it matters.
Dec 7 '05 #10

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

Similar topics

7
3260
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
7
1550
by: Peter | last post by:
I want to create a multidemensional arraylist. Seeing as they don't exist I was wondering if there is a way to create a class that works like one. I basically want to use it like this Dim MyArray as classNewArray MyArray.add("Data1", "Data2") or the looping claus....
4
9682
by: mflll | last post by:
I am looking into the different techniques of handling arrays of edit boxes in Java Script. The first program below works fine. However, are there better ways of doing this, where the person writing the JavaScript doesn't have to pass the index in the "onChange" event name. I thought that one might be able to use "this.value" or compare this as
8
12960
by: Jim | last post by:
In a C# project I'm working on for an iterative design application, I need to dispose of a large arrray of a struct object and reinitialize the array between iterations. That is, the user starts a design, and the program creates an array of objects defined as follows: public struct DES_TYPE { public string short_string;
9
2107
by: JoeC | last post by:
I am crating a new version of my map game and my map will be a 2d array. I had problems trying to create a 2d array dynamically, in fact C++ won't let me do it. My question is how to create the size of array I need at run time without using too much memory or going over the allotted size if I choose to use this object for a different game. One idea I have is to create space * spaces = new space; then have all my accessors just convert...
1
2919
by: stevedub | last post by:
I am having some trouble configuring my array to read from a sequential file, and then calling on that to fill an array of interests. I think I have the class set up to read the file, but when I run my program the rates array does not get the information. I think my problem is where I am actuall calling the array index, but I am not sure how to do this. Here is my code: /* * MortFrame.java * * Created on February 24, 2008, 7:28 PM */...
10
1884
by: ALKASER266 | last post by:
Hey guyz I have a prac and I am beginner and I did this code> Is my code is complete and if is it not complete how i can complete it? and how i can arrange it more? How I can make my driver to an array that generates an array of 20 students instead of my way of driver to enter it manually? THANK YOU VERY MUCH I will put the question then I will put my answer It is two codes one is Student which is the main one and the other one is...
2
1410
by: alefajnie | last post by:
class A: this_is_original_variable_only_for_one_inctance = 0 def __init__(self, v): self.this_is_original_variable_only_for_one_inctance = v class B: this_is_common_for_all_instances =
5
3642
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call 10 member functions. Can switch be replaced to member function pointer array? Please provide me an example of source code to show smart pointer inside class. Thanks....
0
8504
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
8922
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
8751
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
8771
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
7581
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
6429
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
4299
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
4519
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2195
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.