By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,290 Members | 1,195 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,290 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Share this Question
Share on Google+
9 Replies


P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
"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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.