C# Programming - Get and Set Private Properties using Reflection

in #programming7 years ago


It can be frustrating when you're using an API and some properties you require are set as private. This certainly was the case when attempting to resume a video using the YouTube V3 API recently

 Here is a code snippet on how to get and set private properties using Reflection 

private static void SetPrivateProperty(Object obj, string propertyName, object value)
{
    var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    if (propertyInfo == null) return;
    propertyInfo.SetValue(obj, value, null);
}

private static object GetPrivateProperty(Object obj, string propertyName)
{
    if (obj == null) return null;
    var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    return propertyInfo == null ? null : propertyInfo.GetValue(obj, null);
}



Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.030
BTC 64118.79
ETH 3390.14
USDT 1.00
SBD 2.51