Mega Code Archive

 
Categories / C# Book / 09 Reflection
 

0627 Dynamically Invoking a Member

Once you have a MemberInfo object, you can dynamically call it or get/set its value. This is called dynamic binding or late binding. To illustrate, the following uses ordinary static binding: using System; using System.Reflection; using System.Collections.Generic; class Program { static void Main() { string s = "Hello"; int length = s.Length; } } Here's the same thing performed dynamically with reflection: using System; using System.Reflection; using System.Collections.Generic; class Program { static void Main() { object s = "Hello"; PropertyInfo prop = s.GetType().GetProperty("Length"); int length = (int)prop.GetValue(s, null); // 5 } }