Object - GetPropertyOrField

A T extension method that gets property or field.

Try it

public static void Main()
{
	var obj = new PropertyFieldModel<int>();
	
	//C# Extension Method: Object - GetPropertyOrField	
    var ConstField = obj.GetPropertyOrField("ConstField");
	var StaticProperty = obj.GetPropertyOrField("StaticProperty");
	var VirtualProperty = obj.GetPropertyOrField("VirtualProperty");

	Console.WriteLine(ConstField.GetDeclaraction());
	Console.WriteLine(StaticProperty.GetDeclaraction());
	Console.WriteLine(VirtualProperty.GetDeclaraction());
}

public class PropertyFieldModel<T>
{
	public const int ConstField = 1;
    public static int StaticField;
    public readonly int ReadOnlyField = 1;
    public volatile int VolatileField = 1;
	
    public static int StaticProperty { get; set; }
    public virtual int VirtualProperty { get; set; }
    internal int InternalProperty { get; set; }
    private int PrivateProperty { get; set; }
}

View Source
using System.Reflection;

public static partial class Extensions
{
    /// <summary>A T extension method that gets property or field.</summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="name">The name.</param>
    /// <returns>The property or field.</returns>
    public static MemberInfo GetPropertyOrField<T>(this T @this, string name)
    {
        PropertyInfo property = @this.GetProperty(name);
        if (property != null)
        {
            return property;
        }

        FieldInfo field = @this.GetField(name);
        if (field != null)
        {
            return field;
        }

        return null;
    }
}