Reputation: 21
this might be a simple fix but I can't seem to find anything about it. I am very new to C# if it's not obvious.
I'm passing a list of objects from my main method but I haven't been able to use the properties of the objects. I want to use a property called "Asset" This is my code:
private void GetDueDates(List<object> objects)
{
Type myType = objects.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
if(props.Contains(Asset)
{
doStuff();
}
}
I thought if I got the type of object then I could use the correct property but that didn't work. Do I even need to find which type it is?
Upvotes: 0
Views: 128
Reputation: 9270
If you know what type all of the objects in objects
should be, then objects
should be a list of that type, instead of a list of object
(so List<MyType>
). At this point, you can simply refer to objects[0].Asset
, since all of the objects in the list are of type MyType
.
If you still want objects
to be a List<object>
, then you'll have to typecast each of the objects in the list to a MyType
in order to use the Asset
property of the MyType
class: ((MyType)objects[0]).Asset
.
If you do this, and you aren't sure that all of the objects in the list are actually of type MyType
, you need to check that:
if (objects[0] is MyType)
{
// do stuff with ((MyType)objects[0]).Asset
}
Upvotes: 0
Reputation: 1503729
Asset
isn't a valid expression here, unless you've actually got a variable called Asset
somewhere. You want to find out if the name of any property is Asset
... and you want to do it on each object, not on the list itself:
foreach (var item in objects)
{
var props = item.GetType().GetProperties();
var assetProperty = props.FirstOrDefault(p => p.Name == "Asset");
if (assetProperty != null)
{
var value = assetProperty.GetValue(item, null);
// Do stuff...
}
}
Alternatively, if you're only looking for a public property, you can pass the name to GetProperty
:
foreach (var item in objects)
{
var assetProperty = item.GetType().GetProperty("Asset");
if (assetProperty != null)
{
var value = assetProperty.GetValue(item, null);
// Do stuff...
}
}
Having said this, it would be cleaner if you had an interface or something similar:
var assetItems = objects.OfType<IHasAsset>();
foreach (var assetItem in assetItems)
{
var asset = assetItem.Asset;
...
}
Upvotes: 1