I see that the "Quick Watch" window has access to all properties, irrespective of access restrictions (internal, protected, private) of a class in a library, even when the library is referenced in a totally different app,lib and namespace. Whereas I am not finding a way to access these using "reflection". I am especially trying to "read" (note - just read) the internal property of an assembly. If this is not possible by design of how "internal" works (not accessible outside the same namespace), how come it is "read" by the "Quick watch" window in VS.NET?
Here is the example code I used:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestLib
{
public class TestInteralProp
{
internal string PropertyInternal
{
get { return "Internal Property!"; }
}
protected string PropertyProtected
{
get { return "Protected Property!"; }
}
string PropertyPrivate
{
get { return "Private Property!"; }
}
public string PropertyPublic
{
get { return "Public Property!"; }
}
protected internal string PropertyProtectedInternal
{
get { return "Protected Internal Property!"; }
}
}
}
When i create an object for TestInernalProp class, I can see all 4 properties in quickwatch -
And when I use reflection to access any of these except the public property (PropertyPublic), i get a null reference exception.
//this works
propTestObj.GetType().InvokeMember("PropertyPublic", System.Reflection.BindingFlags.GetProperty, null, propTestObj, null);
//this fails (obviously)
propTestObj.GetType().InvokeMember("PropertyInternal", System.Reflection.BindingFlags.GetProperty, null, propTestObj, null);
//this works
propTestObj.GetType().GetProperty("PropertyPublic").GetValue(propTestObj, null);
//this fails again
propTestObj.GetType().GetProperty("PropertyInternal").GetValue(propTestObj, null)
I am not clear about how "Quick Watch" can gain access to these.
Use these flags
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
The GetProperty
flag is not required for this operation. You might want to add Static
as well.
Note: You can combine the flags with |
, because their integer values are powers of two. See this SO answer.
NOTE (In response to Lalman's and shanks's concern about security issues of Reflection)
There is always a way to write bad or dangerous code. It is up to you to do it or not. Reflection is not the regular way of doing things, rather is it meant for the programming of special tools, like o/r-mappers or analysis tools. Reflection is very powerful; however, you should use it wisely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With