dynamically get/set member value
Published: 16. November 2011 | Updated: 16. November 2011License: Microsoft Public License (MS-PL)
Categories: Framework » Reflection
Tags: C# Reflection
Snippet shows how to get or set property of object using reflection
Import namespace
using System.Reflection;
Code
// create or get instance var obj = new MyClass(); // get PropertyInfo by name PropertyInfo property = obj.GetType().GetProperty("PropertyName"); // set value 'text' property.SetValue(obj, "text", new object[0]); // get value string value = (string)property.GetValue(obj, new object[0]); Console.WriteLine(value);
Class used in example
public class MyClass { public string PropertyName { get; set; } }Console Output:
text
| Send us feedback about this snippet » |





