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

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

Fiducia Solutions said...

Fiducia Solutions is an ISO 9001:2015 certified institute providing course certifications to all its students. We, at Fiducia Solutions, see to it that the candidate is certified and entitled to bag a good position in acclaimed companies. We provide certificates that are valued, and our alumni reputation proves that we are good at what we offer.

And that is not all! We are known to provide 100% live project training and 100% written guaranteed placements to our students. That’s what makes us the best PHP/ HR/ Digital Marketing training institutes in Noida and Ghaziabad.

PHP Training Institute in Noida
HR Training Institute in Noida
Digital Marketing Training Institute in Noida
Android Training Institute in Noida