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

G

Guest

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
 
J

Jon Skeet [C# MVP]

Haobin said:
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];
 
D

Daniel Bass

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 said:
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?
 
W

William Stacey [MVP]

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 said:
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
 
G

Guest

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 said:
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
 
J

Jon Skeet [C# MVP]

Haobin said:
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.
 
G

Guest

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 said:
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
 
B

Bjorn Abelli

...

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
 
J

Jon Skeet [C# MVP]

Haobin said:
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();

alDataSets.Add(expData1);

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
 
D

Daniel Bass

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 said:
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 said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top