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?)
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With