Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch a value of a property of an object in ArrayList

Tags:

c#

.net

arraylist

I have initialized an ArrayList in C# for windows form application. I am adding new objects with few properties of each object in the ArrayList, such as:

ArrayList FormFields = new ArrayList();

CDatabaseField Db = new CDatabaseField();
Db.FieldName = FieldName; //FieldName is the input value fetched from the Windows Form
Db.PageNo = PageNo; //PageNo, Description, ButtonCommand are also fetched like FieldName
Db.Description = Description;
Db.ButtonCommand = ButtonCommand;
FormFields.Add(Db);

Now When I want to check only the FieldName of each object in the ArrayList (suppose there are many objects in the ArrayList). How can I do that??

I tried:

for(int i=0; i<FormFields.Count; i++) 
{
    FieldName = FormFields[i].FieldName;
}

But this is generating error (in the IDE). I am new to C# programming, so can someone help me with this??

Error: Error 21 'object' does not contain a definition for 'FieldName' and no extension method 'FieldName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

like image 433
Somdip Dey Avatar asked Dec 25 '22 03:12

Somdip Dey


2 Answers

Finally figured out the answer. I tried to cast the objects for each object saved in the arraylist and finally could fetch the required field of each object:

for (int i = 0; i < FormFields.Count; i++)
{
     CDatabaseField Db = (CDatabaseField)FormFields[i];
     Label1.Text = Db.FieldName; //FieldName is the required property to fetch
}
like image 28
Somdip Dey Avatar answered Jan 21 '23 22:01

Somdip Dey


ArrayList holds objects. It's not generic and type safe.That's why you need to cast your object to access it's properties. Instead consider using generic collections like List<T>.

var FormFields = new List<CDatabaseField>();
CDatabaseField Db = new CDatabaseField();
...
FormFields.Add(Db);

Then you can see that all properties will be visible because now compiler knows the type of your elements and allows you to access members of your type in a type-safe manner.

like image 133
Selman Genç Avatar answered Jan 21 '23 21:01

Selman Genç