Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property/variable from unknown object

I have a list of 'object' that has different kinds of objects in it. I need to be able to edit/read a property of the objects that all of them have, but I don't know how to do that.

List<object> objects = new list<object>();
SomeObject obj;

objects.add(obj);

Int value = objects(0).somevariable;

But it obviously can't read 'somevariable' since the code doesn't know that the object has it. Is doing this possible since all the objects in the list has the variable 'somevariable'?

Also, I'm using XNA, but that probably doesn't make any difference.

Edit: Thanks everybody for your answers, I'll try them tomorrow when I get on my computer.

like image 479
user2407063 Avatar asked Aug 25 '26 14:08

user2407063


1 Answers

If you can modify those classes and make sense on your scenario, you could define a common interface

public interface IMyInterface
{
     int Somevariable { get; set;}
}

and let your classes implement this interface, then you will be able to create a generic list like this

var objects = new List<IMyInterface>();
int value = objects[0].Somevariable;
like image 52
Claudio Redi Avatar answered Aug 28 '26 05:08

Claudio Redi



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!