473,397 Members | 1,950 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,397 software developers and data experts.

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 4903
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.ToString(), or
are you looking for something more generic?
"Daan" <d_*****@IDONTLIKESPAMhotmail.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.ToString(), 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.ServiceOrder'because 'SMOBY.ServiceOrder'
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_*****@IDONTLIKESPAMhotmail.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.ToString(), 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.ServiceOrder'because 'SMOBY.ServiceOrder'
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[] GetAllVariablesAsArray()
{
FieldInfo[] fields =
this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.DeclaredOnly);
// 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.GetAllVariablesAsArray())
{
Console.WriteLine(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.com>
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(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.DeclaredOnly);
// 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
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)) ...
7
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...
4
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...
8
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...
9
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...
1
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...
10
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...
2
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
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...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.