C# Tutorial - Using Reflection to Get Object Information

Skill

C# Tutorial - Using Reflection to Get Object Information

Posted in:

Every once in a while you might want to know what fields, properties, or events a certain type of object contains at runtime. A common use for this information is serialization. .NET contains lots of different serialization techniques, like binary and XML, but sometimes you just have to roll your own. This tutorial is going to demonstrate how to get a list of public fields, properties, and events from objects at runtime.

First, let's create a simple object that contains some fields, properties, and events. I'll be using this object throughout the rest of the tutorial.

public class MyObject
{
   //public fields
   public string myStringField;
   public int myIntField;
   public MyObject myObjectField;

   //public properties
   public string MyStringProperty { get; set; }
   public int MyIntProperty { get; set; }
   public MyObject MyObjectProperty { get; set; }

   //public events
   public event EventHandler MyEvent1;
   public event EventHandler MyEvent2;
}

The .NET class that gives us access to all of this is the Type class. To get a Type object, we simply use the typeof keyword:

Type myObjectType = typeof(MyObject);

To get a list of public fields in an object, we'll use Type's GetFields method:

Type myObjectType = typeof(MyObject);

System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields();

foreach (System.Reflection.FieldInfo info in fieldInfo)
   Console.WriteLine(info.Name);

// Output:
// myStringField
// myIntField
// myObjectField

An important thing to note here is that the fields are not guaranteed to come out in any particular order. If you use GetFields, you should never depend on the order being consistent. The FieldInfo class that gets returned actually contains a lot of useful information. It also contains the ability to set that field on an instance of MyObject - that's where the real power comes in.

MyObject myObjectInstance = new MyObject();

foreach (System.Reflection.FieldInfo info in fieldInfo)
{
   switch (info.Name)
   {
      case "myStringField":
         info.SetValue(myObjectInstance, "string value");
         break;
      case "myIntField":
         info.SetValue(myObjectInstance, 42);
         break;
      case "myObjectField":
         info.SetValue(myObjectInstance, myObjectInstance);
         break;
   }
}

//read back the field information
foreach (System.Reflection.FieldInfo info in fieldInfo)
{
   Console.WriteLine(info.Name + ": " +
      info.GetValue(myObjectInstance).ToString());
}

// Output:
// myStringField: string value
// myIntField: 42
// myObjectField: MyObject

Combining this ability with the ability to create custom attributes provides a framework on which almost any serialization technique can be built.

Properties and events are retrieved almost identically to fields:

Type myObjectType = typeof(MyObject);

//Get public properties
System.Reflection.PropertyInfo[] propertyInfo =
     myObjectType.GetProperties();

foreach (System.Reflection.PropertyInfo info in propertyInfo)
   Console.WriteLine(info.Name);

// Output:
// MyStringProperty
// MyIntProperty
// MyObjectProperty

//Get events
System.Reflection.EventInfo[] eventInfo =
   myObjectType.GetEvents();

foreach (System.Reflection.EventInfo info in eventInfo)
   Console.WriteLine(info.Name);

// Output:
// MyEvent1
// MyEvent2

The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance. It also gives you the ability to individually receive the get and set accessors as MethodInfo classes through the GetAccessors method.

An EventInfo object gives you lots of information about the event and the ability to add events to instances of MyObject.

I think that about does it. Hopefully this helps anyone out there wanting to get information about objects at runtime. If something didn't make sense, or you've got other questions, just leave them in the comments.

Dykam
12/03/2008 - 03:06

Thanks, this is the first, clear tutorial about reflection. Will solve some of my problems I had.

reply

Sam
03/27/2009 - 22:48

What a helpful and beautifully written page. No bullshit, no crappy code, just what I was looking for.

Thank you so much.

reply

Nathaniel
05/11/2009 - 23:24

Can you get the name of the origional object through reflection as well? In you example you are getting information about members of the object you've been passed. I need to get the origional name of the object instance. In one of your first example this would be "myObjectInstance". Is this accessible at all?

reply

The Reddest
05/12/2009 - 00:21

The JIT doesn't really keep variable names around at runtime, so I don't believe it's possible.

reply

Anonymous
05/25/2009 - 09:40

How to find the list of classes available in .cs file using reflection......

reply

Austin
05/26/2009 - 16:35

Thanks for the explanation. its so clear

reply

Latha
10/28/2009 - 01:59

super tutorial....keep it up....

reply

Anonymous
04/11/2010 - 02:51

THANKSSSS!!!

reply

Promesses
10/21/2010 - 07:23

is it possible to get the property of the property myObject?

reply

vvv
11/16/2010 - 02:42

great... simple and effective

reply

Anonymous
02/20/2011 - 10:34

how can we get summary information too?

reply

Isaac
03/16/2011 - 07:19

Thanks!!!

reply

Pallavi Pingale
03/17/2011 - 07:00

nice example and well explained..thanks

reply

Noone
03/20/2011 - 15:14

This is just too beautiful. Thanks pal (sniff)

reply

Winston
05/12/2011 - 05:08

"the fields are not guaranteed to come out in any particular order"

Is there a way to get the correct order of the objects?

reply

The Reddest
05/12/2011 - 06:03

Since the order doesn't matter at compile-time or run-time, there is no concept of 'correct order'. If you mean the order in which they appear in your source code, then no, there's no way to do that.

reply

Lolo
07/27/2011 - 08:49

I agree. Finally a Reflection article thats totally understandable and accesssible.
Thank you!
Very well written, and has given me enough knowledge to "take it from here". (after quite alot of googling)

reply

Anonymous
01/20/2012 - 17:31

Excellent Article.
If it is hard to get the order of the field/property as it is declared in source code using GetFields or GetProperties, I got a question, how DataGridView class gets these field order details from source code, when binding the list of object to it.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.