Reputation: 1309
im trying to work out if you can access an object that was added to a list (of objects) something like this:
public class nearshop_data
{
public String r_name { get; set; }
public String r_desc { get; set; }
public String loc_lat { get; set; }
public String loc_lon { get; set; }
}
then adding to that list as you would
shop_data = new nearshop_data();
lo = new List<object>();
for (int i = 0; i < count; i++) {
shop_data.r_name = stuff.results[i].name;
shop_data.r_desc = stuff.results[i].vicinity;
shop_data.loc_lat = stuff.results[i].geometry.location.lat;
shop_data.loc_lon = stuff.results[i].geometry.location.lng;
lo.Add(shop_data);
}
then i want to retrieve that in another class say in the code behind and here is where it all fails... as i cant actually access the properties of that object
any ideas on how to rewrite the code or what to use?
I'm guessing when I get the instance of that list in my code behind and lets say retrieve it at index 0 its still boxed in (or am i wrong?) - i vaguely remember something like this was done in java
Upvotes: 0
Views: 4479
Reputation: 30922
I think the problem is that you're using List<object>
instead of List<nearshop_data>
which is effectively boxing the type.
If you need to keep it like this you'd need to cast the object to the appropriate type:
nearshop_data firstElement = (nearshop_data)lo[0];
or even better use a List<nearshop_data>
in the first place.
In addition because nearshop_data
is a reference type, and you only instantiate it once, you are only adding the pointer to the same instance of shop_data
each time. Meaning you'll only end up with one element with the values equal to that of the last loop iteration.
Upvotes: 4
Reputation: 45155
You need to cast the item from the list back to it's specific class:
nearshop_data myitem = lo[0];
Of course you might want to check the type of the open before you try and cast (otherwise it will throw an exception). You can either do this:
if (lo[0] is nearshop_data)
{
// do your cast here
}
or:
nearshop_data myitem = lo[0] as nearshop_data;
if (myitem != null)
{
// myitem is a nearshop_data instance
}
Of course, better would be to use a more specific class in your generic list. List<object>
is really no more useful than the old ArrayList
. If you only need nearshop_data
items then just use List<nearshop_data>
. If you need a hetreogenous list then just use the most specific base class (or interface) that will cover all the items you need to store.
Upvotes: 1