I have no idea how to describe my issue in the right terms, sorry. My assignment is pretty simple, but I am having a tough time with an ArrayList in c#. If I had an array of objects and that object had a method named jump I could call it by
arrObjects\[index\].jump();
But my assignment wants me to use an ArrayList, so im trying to avoid using arrays or a list. I would like to compare input entered from a User with a objects method that returns a variable.(Using a for loop to check every existing objects method.) If I was using arrays it would look like
if( arrObjects\[index\].ReturnName == Textbox.Text )
{
//Do Something
}
I would like to achieve the same using an ArrayList. Any advice would be appreciated.
Apologies for not sharing code, not familiar with using stackoverflow <3
I have tried doing it the way I do with arrays as well as looking for a solution all over the web but my brain is fried.
CodePudding user response:
So I think what you are trying to say is that the problem is that an ArrayList just stores "objects" and doesn't know the Type of the object. Unlike List which uses Generics so it knows the type.
So then in this case you have to perform an explicit cast before you can call your method. So if your object is of type Person
, then you could do this
if((arrObjects[index] as Person).ReturnName().Equals(Textbox.Text))
{
}
This is why List is considered better for such cases. In fact, ArrayList should not really be used any more. See also this: ArrayList vs List<> in C#