Wednesday, 13 April 2016

Get and Set Private Properties using Reflection in C#


It's frustrating when you're using an API and some properties you requuire are set as private. This certainly was the case when attempting to resume a video using the YouTube V3 API the other day.

Here is a code snippet on how to set private properties using Reflection.
Code Snippet
  1. private static void SetPrivateProperty<T>(Object obj, string propertyName, object value)
  2. {
  3. var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  4. if (propertyInfo == null) return;
  5. propertyInfo.SetValue(obj, value, null);
  6. }
  7. private static object GetPrivateProperty<T>(Object obj, string propertyName)
  8. {
  9. if (obj == null) return null;
  10. var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  11. return propertyInfo == null ? null : propertyInfo.GetValue(obj, null);
  12. }
End of Code Snippet

3 comments:

Anonymous said...

Great Post,really it was very helpful for us.
Thanks a lot for sharing!
I found this blog to be very useful!!
JAVA training in Bangalore

webgurukuul said...

Thank you for sharing

AMBE AI TECHNOLOGIES said...

This is a fantastic read! Your points are well-researched and clearly explained. I appreciate the time and effort you put into creating such informative content. Keep up the great work!