472,954 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

How to access an array element in a member of ArrayList?

Hi everyone,
I have an ArrayList whose members are classes. These classes are derived from a same base class. The base class has a floating point array and a string. How do I access each element in the floating point array in a member of the ArrayList?
Any help would be greatly appreciated.

Haobin

Nov 16 '05 #1
9 4008
Haobin <an*******@discussions.microsoft.com> wrote:
I have an ArrayList whose members are classes. These classes are
derived from a same base class. The base class has a floating point
array and a string. How do I access each element in the floating
point array in a member of the ArrayList?
Any help would be greatly appreciated.


As always in programming, the trick is to break the problem down:

1) How do I get an element in my array list as the base class?
2) How do I access the floating point array in an instance of my base
class?
3) How do I access each element in a floating point array?
1) is easy - just cast:

BaseClass foo = (BaseClass) myArrayList[index];

2) depends on your base class

3) is easy - just index:

float f = myFloatArray[index];

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
Haobin,

I assume this is the scenario you are talking about...
----------------------------------------------------------------------------
--------------------
class SomeObject
{
public float fMyNumber; // or is it an array of floats? doesn't matter
either way.
public string szMyString;
...
}

ArrayList aryOfObjects... // contains, or will contain loads of SomeObjects
----------------------------------------------------------------------------
--------------------
void SomeMethodSomewhere()
{

//
// for all objects in the array
//

SomeObject so;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
if ( aryOfObjects[a] is SomeObject )
{
so = (SomeObject)aryOfObjects[a];
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float to
some predifined list
listbox2.Items.Add ( so.szMyString.ToString() ); // add string
to some predifined list
}
else
{
// report some error?
continue;
}

}

}
----------------------------------------------------------------------------
--------------------

Does that make sense? Of course it's better code practice to keep your
member variables private, and access them through properties.
Let me know if you have any more probs.

Dan.

"Haobin" <an*******@discussions.microsoft.com> wrote in message
news:04**********************************@microsof t.com...
Hi everyone,
I have an ArrayList whose members are classes. These classes are derived from a same base class. The base class has a floating point array and a
string. How do I access each element in the floating point array in a member
of the ArrayList? Any help would be greatly appreciated.

Haobin

Nov 16 '05 #3
Below is a small twist that can be slightly more efficient I guess as you
check the type and cast at same time.

SomeObject so = null;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
so = aryOfObjects[a] as SomeObject;
if ( so == null )
throw new MyException("foo");
listbox1.Items.Add(so.fMyNumber.ToString());
....
}

--
William Stacey, MVP
void SomeMethodSomewhere()
{

//
// for all objects in the array
//

SomeObject so;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
if ( aryOfObjects[a] is SomeObject )
{
so = (SomeObject)aryOfObjects[a];
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float to some predifined list
listbox2.Items.Add ( so.szMyString.ToString() ); // add string
to some predifined list
}
else
{
// report some error?
continue;
}

}

}
-------------------------------------------------------------------------- -- --------------------

Does that make sense? Of course it's better code practice to keep your
member variables private, and access them through properties.
Let me know if you have any more probs.

Dan.

"Haobin" <an*******@discussions.microsoft.com> wrote in message
news:04**********************************@microsof t.com...
Hi everyone,
I have an ArrayList whose members are classes. These classes are derived from a same base class. The base class has a floating point array and a
string. How do I access each element in the floating point array in a

member of the ArrayList?
Any help would be greatly appreciated.

Haobin



Nov 16 '05 #4
Hi Jon and Daniel
Thanks for your replies
I modified my code based on your replies. It passed compilation but I got "InvalidCastException" in runtime at the step 1 in Jon's reply and at the line "so = (SomeObject)aryOfObjects[a];" in Daniel's reply. What could be wrong
I appreciate your help

Haobi

----- Daniel Bass wrote: ----

Haobin

I assume this is the scenario you are talking about..
---------------------------------------------------------------------------
-------------------
class SomeObjec

public float fMyNumber; // or is it an array of floats? doesn't matte
either way
public string szMyString
..
ArrayList aryOfObjects... // contains, or will contain loads of SomeObject
---------------------------------------------------------------------------
-------------------
void SomeMethodSomewhere(
/
// for all objects in the arra
/

SomeObject so
for ( int a = 0; a < aryOfObjects.Count; a++

if ( aryOfObjects[a] is SomeObject

so = (SomeObject)aryOfObjects[a]
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float t
some predifined lis
listbox2.Items.Add ( so.szMyString.ToString() ); // add strin
to some predifined lis

els

// report some error
continue

---------------------------------------------------------------------------
-------------------

Does that make sense? Of course it's better code practice to keep you
member variables private, and access them through properties
Let me know if you have any more probs

Dan

"Haobin" <an*******@discussions.microsoft.com> wrote in messag
news:04**********************************@microsof t.com..
Hi everyone
I have an ArrayList whose members are classes. These classes are derive from a same base class. The base class has a floating point array and
string. How do I access each element in the floating point array in a membe
of the ArrayList Any help would be greatly appreciated
Haobi

Nov 16 '05 #5
Haobin <an*******@discussions.microsoft.com> wrote:
Thanks for your replies.
I modified my code based on your replies. It passed compilation but I
got "InvalidCastException" in runtime at the step 1 in Jon's reply
and at the line "so = (SomeObject)aryOfObjects[a];" in Daniel's
reply. What could be wrong?
I appreciate your help.


Basically exactly what the exception says: you're trying to cast
something which isn't an instance of your class.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
Hi Jon, Daniel and William
Thank you very much
Here is my test code
Haobi

using System
using System.Drawing
using System.Collections
using System.Windows.Forms
using System.Data

namespace DrawTes

public class Form1 : System.Windows.Forms.For

public ArrayList alDataSets = new ArrayList()

private System.Windows.Forms.Button button1

private void button1_Click(object sender, System.EventArgs e

float expData1,expData2
Random rand = new Random()

expData1 = (float)rand.NextDouble()
expData2 = (float)rand.NextDouble()

DataSets dataset1 = new DataSets();
dataset1.fData = expData1
dataset1.strDesc = "X"
alDataSets.Add(expData1)

DataSets dataset2 = new DataSets();
dataset2.fData = expData2
dataset2.strDesc = "Y"
alDataSets.Add(expData2)

label1.Text = alDataSets.Count.ToString()

DataSets dataset3
dataset3= null
dataset3 = (DataSets)alDataSets[0]; //get "System.InvalidCastException
string strFirst
strFirst = dataset3.strDesc
label2.Text = strFirst

DataSets dataset4
dataset4 = (DataSets)alDataSets[1]; //get "System.InvalidCastException
string strSecond
strSecond = dataset4.strDesc
label3.Text = strSecond

//the base clas
using System

namespace DrawTes

public class DataSet

public DataSets(

private float arData
private string desc

public string strDes

get{return desc;
set{desc = value;

public float fDat

get{return arData;
set{arData = value;

----- Jon Skeet [C# MVP] wrote: ----

Haobin <an*******@discussions.microsoft.com> wrote
Thanks for your replies
I modified my code based on your replies. It passed compilation but
got "InvalidCastException" in runtime at the step 1 in Jon's repl
and at the line "so = (SomeObject)aryOfObjects[a];" in Daniel'
reply. What could be wrong
I appreciate your help


Basically exactly what the exception says: you're trying to cast
something which isn't an instance of your class

Could you post a short but complete program which demonstrates th
problem

See http://www.pobox.com/~skeet/csharp/complete.html for details o
what I mean by that

--
Jon Skeet - <sk***@pobox.com
http://www.pobox.com/~skee
If replying to the group, please do not mail me to

Nov 16 '05 #7
Haobin <an*******@discussions.microsoft.com> wrote:
Hi Jon, Daniel and William,
Thank you very much.
Here is my test code.
The relevant lines are:
expData1 = (float)rand.NextDouble();
expData2 = (float)rand.NextDouble();
<snip>
alDataSets.Add(expData1);
<snip>
alDataSets.Add(expData2);
dataset3 = (DataSets)alDataSets[0];
//get "System.InvalidCastException"


So you've added two *floats* to the ArrayList, but then you're trying
to cast them to DataSets.

I think you actually meant:

alDataSets.Add(dataSet1);

etc

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
"Haobin" wrote...

You get the InvalidCastException because you try to cast to a type which the
object isn't castable to.

The reason for this is found higher up in the code, where we see that you
don't actuallt put objects of that type into the ArrayList:
DataSets dataset1 = new DataSets();
dataset1.fData = expData1;
alDataSets.Add(expData1); // <-

DataSets dataset2 = new DataSets();
dataset2.fData = expData2;
alDataSets.Add(expData2); // <-
You have put two floats into the ArrayList, not the whole DataSets.
dataset3 = (DataSets)alDataSets[0]; //get "System.InvalidCastException"


The lines I've marked above should probably be the following instead:

alDataSets.Add(dataset1b);

alDataSets.Add(dataset2);

// Bjorn A
Nov 16 '05 #9
William,

I've not really come across the "as" keyword in C#. Suppose never needed to
use it, so never find it.

I'd still go for my solution to it, just from a readability point of view...
it seems most logical, well to me anyway, to say if this object is a certain
type, then assign it, rather than assigning the object as a type to another
object, and if that fails then the object wasn't of the type we specified.

As far as efficiency goes, it seems negligible.

Interesting though.
Thanks.
Dan.

"William Stacey [MVP]" <st***********@mvps.org> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
Below is a small twist that can be slightly more efficient I guess as you
check the type and cast at same time.

SomeObject so = null;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
so = aryOfObjects[a] as SomeObject;
if ( so == null )
throw new MyException("foo");
listbox1.Items.Add(so.fMyNumber.ToString());
....
}

--
William Stacey, MVP
void SomeMethodSomewhere()
{

//
// for all objects in the array
//

SomeObject so;
for ( int a = 0; a < aryOfObjects.Count; a++ )
{
if ( aryOfObjects[a] is SomeObject )
{
so = (SomeObject)aryOfObjects[a];
listbox1.Items.Add ( so.fMyNumber.ToString() ); // add float

to
some predifined list
listbox2.Items.Add ( so.szMyString.ToString() ); // add string to some predifined list
}
else
{
// report some error?
continue;
}

}

}


--------------------------------------------------------------------------
--
--------------------

Does that make sense? Of course it's better code practice to keep your
member variables private, and access them through properties.
Let me know if you have any more probs.

Dan.

"Haobin" <an*******@discussions.microsoft.com> wrote in message
news:04**********************************@microsof t.com...
Hi everyone,
I have an ArrayList whose members are classes. These classes are
derived from a same base class. The base class has a floating point array and a
string. How do I access each element in the floating point array in a

member
of the ArrayList?
Any help would be greatly appreciated.

Haobin


Nov 16 '05 #10

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

Similar topics

4
by: theo | last post by:
Program flow...load file,then extract the xml text tags from the file,then the number of Xml tags retrieved from the file determines the number of dropdownlist controls instanciated in the...
3
by: S | last post by:
Hi there, Here's a question for ya: I'm serializing something that looks like this: Class Widget --> My base class public ArrayList TextGroups --> An...
14
by: Mike | last post by:
I had a question about threading and access to private class variables. I am developing a windows service which has a class inside of it which will receive various asynchronous calls to it via...
9
by: Steve | last post by:
Hello, I created a structure ABC and an array of type ABC Public Structure ABC Dim str1 As String Dim int1 As Integer End Structure Public ABC1 As New ABC, ABC2 As New ABC
24
by: RyanTaylor | last post by:
I have a final coming up later this week in my beginning Java class and my prof has decided to give us possible Javascript code we may have to write. Problem is, we didn't really cover JS and what...
9
by: gk245 | last post by:
I have something like this: struct block { int x; int y; float z; }
7
by: Adam Honek | last post by:
Is there a direct way to remove one entry from a one dimensional array? I keep looking but either my eyes are funny or it isn't there. Must we really create a temp array and copy all but 1 of...
9
by: Brian Tkatch | last post by:
I'm looking for a simple way to unique an array of strings. I came up with this. Does it make sense? Am i missing anything? (Testing seems to show it to work.) Public Function Unique(ByVal...
6
by: Urs Thuermann | last post by:
With offsetof() I can get the offset of a member in a struct. AFAICS, it is portable and clean to use this offset to access that member. I need to do something like this struct foo { struct...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
1
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.