2

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?) 
1
  • Though you've got different answers already, I guess you should concern tha answer by cdiggins, if all the element of your ArrayList are of one and the same type, as there is no sense in a more common ArrayList then. Commented Sep 17, 2012 at 3:05

3 Answers 3

5

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Word. My Man! Thanks a bunch. Is this casting something special with ArrayLists? I suspect this is because these could contain objects of different types?
Or you could cast it as ((MyClass)Unit.unitArray[selectedUnit]).DisplayUnitAttributes(), which would throw an invalid cast exception if the object is the wrong type, instead of the generic exception thrown by null object references.
@user1676520: correct, the arraylist stores objects. so when you retrieve you have to cast it from an object.
3

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.

Comments

1

You could use Enumerable.OfType Method to get the necessary subarray. Something like this:

foreach (YourClass obj in Unit.unitArray.OfType<YourClass>())
    obj.DisplayUnitAttributes();

2 Comments

I like this. Never used it before.
@Valamas In love with it too. It's very useful to filter "common-typed" collections with this. On the contrary, I almost never use Enumerable.Cast<T> method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.