Reputation: 13233
Why do I get this error? Here is the code:
MyClass item = new MyClass{ id=1 };
List<object> items = new List<object>();
items.Add(item);
object getitem = items[0];
int itemid = getitem.id; // <-error
In debugger the getitem
object shows as having the id
property, but I can't extract it without getting this error. How do I extract the id
property from this object?
Upvotes: 1
Views: 2998
Reputation: 6684
The compiler doesn't know that the actual object contained in getitem
is of type MyClass
, because you've told it to expect an object, which could be just about anything. Imagine you'd done this instead:
List<object> items = new List<object>();
items.Add( "Hello, World!" );
object getitem = items[0];
int itemid = getitem.id; // <-error
A string
is also an object, so it's perfectly reasonable to put it in a List<object>
. In fact, anything can be put into an object, so the compiler can only guarantee that whatever is in there can do what an object
can do (which is have methods GetHashCode
, Equals
, and ToString
).
Consider making your list more specific:
MyClass item = new MyClass{ id=1 };
List<MyClass> items = new List<MyClass>();
items.Add( item );
MyClass getitem = items[0];
int itemid = getitem.id;
If that's not an acceptable solution, then you'll need to cast the result from the list so the compiler knows it's actually dealing with an instance of MyClass
:
MyClass getitem = (MyClass) items[0];
int itemid = getitem.id;
Upvotes: 7
Reputation: 502
The debugger is smart enough to know what type getitem really is and will display the properties. If you change it to:
MyClass getitem = (MyClass) items[0];
it will work for you. What your doing is casting the object instance to a MyClass type so the compiler knows it has an id property.
Upvotes: 4