Reputation: 33
I have got an c# object and I don't know the type of this object. (i.e. object o) What I know is that this object has a member called 'ID' of type int.
I wanted to get the value of this property but I am not good enough with reflection...
I can get a type and members of this object:
Type type = obj.GetType();
System.Reflection.MemberInfo[] member = type.GetMember("ID");
...but don't know what to do next :-)
Thanks for help in advance Mariusz
Upvotes: 3
Views: 1476
Reputation: 164281
Can you use C# 4 ? In that case, you can use dynamic
:
dynamic dyn = obj;
int id = dyn.ID;
Upvotes: 2
Reputation: 62484
public class TestClass
{
public TestClass()
{
// defaults
this.IdField = 1;
this.IdProperty = 2;
}
public int IdField;
public int IdProperty { get; set; }
}
// here is an object obj and you don't know which its underlying type
object obj = new TestClass();
var idProperty = obj.GetType().GetProperty("IdProperty");
if (idProperty != null)
{
// retrieve it and then parse to int using int.TryParse()
var intValue = idProperty.GetValue(obj, null);
}
var idField = obj.GetType().GetField("IdField");
if (idField != null)
{
// retrieve it and then parse to int using int.TryParse()
var intValue = idField.GetValue(obj);
}
Upvotes: 1
Reputation: 754545
Is this a public property? Is so then the easiest route is to use dynamic
int value = ((dynamic)obj).ID;
Upvotes: 4
Reputation: 1499760
You can use:
Type type = obj.GetType();
PropertyInfo property = type.GetProperty("ID");
int id = (int) property.GetValue(obj, null);
PropertyInfo
because you know it's a property, which makes things easierGetValue
to get the value, passing in obj
as the target of the property and null
for indexer arguments (as it's a property, not an index)int
as you already know it's going to be an int
Jared's suggestion of using dynamic
is good too, if you're using C# 4 and .NET 4, although to avoid all the brackets I'd probably write it as:
dynamic d = obj;
int id = d.ID;
(unless you needed it in a single expression for some reason).
Upvotes: 5