Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to call method of object indexed in ArrayList in C#

I'm new to C# and I'm writing a program where I have an ArrayList (unitArray) of Unit objects and am trying to call a non-static method on the object referenced in the ArrayList. I try to access the specific object and call it's method but it doesn't work. I'd be grateful for help resolving this issue.

Unit.unitArray[selectedUnit].DisplayUnitAttributes()

I get the following exception:

'object' does not contain a definition for 'DisplayUnitAttributes' and no extension method 'DisplayUnitAttributes' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) 
like image 953
robertito Avatar asked Jan 30 '26 07:01

robertito


2 Answers

you need to cast the object as its type. In place of MyClass below, substitute your actual class type in.

(Unit.unitArray[selectedUnit] as MyClass).DisplayUnitAttributes()
like image 84
Valamas Avatar answered Feb 01 '26 22:02

Valamas


The type of elements extracted from an ArrayList are System.Object which is the base class of all objects in C#.

You have to cast element to a derived type to access the methods or better yet use a System.Generic.List<T> where T is the type of the elements in the list.

like image 31
cdiggins Avatar answered Feb 01 '26 23:02

cdiggins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!