• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 228
  • Last Modified:

getting property value at runtime using Reflection.

hi guys:

I want to get a property value at runtime but the following code is production

"System.Reflection.TargetException Object does not match target type"

Type t = obj.GetType()// obj is the object whose property is required

PropertyInfo[] pi = t.GetProperties();

foreach (PropertyInfo prop in pi)
{
      string sName      = prop.Name;
                Type t1 = prop.PropertyType;
                        
      object o = prop.GetValue(prop.PropertyType,null);
                                          
}

am I doing somethng wrong?
0
rxraza
Asked:
rxraza
  • 3
1 Solution
 
jdraper3Commented:
A property info object isn't specific to a particular instance, but rather to the type.  Your code is returning the properties of the type successfully, but to actually get a value, you need to specify an instance to get the value from. ('obj' in this example)

For example:

      DateTime obj = new DateTime();
      Type t = obj.GetType(); // obj is the object whose property is required
      PropertyInfo[] pi = t.GetProperties();
     
      foreach (PropertyInfo prop in pi)
      {
        string name = prop.Name;
        object o = prop.GetValue(obj, null);
        Console.WriteLine(name + " : " + o.ToString());
      }

This code will output:

Date : 1/1/0001 12:00:00 AM
Day : 1
DayOfWeek : Monday
DayOfYear : 1
Hour : 0
Millisecond : 0
Minute : 0
Month : 1
Now : 5/13/2005 10:02:30 PM
UtcNow : 5/14/2005 3:02:30 AM
Second : 0
Ticks : 0
TimeOfDay : 00:00:00
Today : 5/13/2005 12:00:00 AM
Year : 1

Hope this helps.
- Justin
0
 
jdraper3Commented:
Was this the answer that you were looking for?
0
 
rxrazaAuthor Commented:
sorry I forgot to close the question.
0
 
jdraper3Commented:
No problem ;)

Glad I could help.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now