Get Field from Object - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Get Field from Object

Demo Code


using System.Text;
using System.Reflection;
using System;//from   w w  w. j a va 2s .  c om

public class Main{
        public static object GetField(this object obj, string name)
        {
            var fieldInfo = obj.GetType().GetField(name,
                BindingFlags.GetProperty |
                BindingFlags.IgnoreCase |
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance);
            return fieldInfo == null ? null : fieldInfo.GetValue(obj);
        }
        public static object GetProperty(this object obj, string name)
        {
            var propertyInfo = obj.GetType().GetProperty(name,
                BindingFlags.GetProperty |
                BindingFlags.IgnoreCase |
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance);
            return propertyInfo == null ? null : propertyInfo.GetValue(obj, null);
        }
}

Related Tutorials