What's the "variable"? You can do it with the member of some class or structure, a field or property, no matter if it is private or not. You will need to know how to use Reflection and have a variable of the class of structure declaring your member, having only a reference to your member is not enough, and not required.
This is the schema:
- You have an instance
Instance
of class or structure which declare a member you need. Obtain its type T
using GetType()
. It will return variable of the type System.Type
and assign to T
. - For a field, call
T.GetField(String, BindingFlags)
by name. If a field is public, second parameter is not needed, if not, use System.Reflection.BindingFlags | System.Reflection.NonPublic
. If the member is static, also OR System.Reflection.Static
. - For a property, call
T.GetProperty(String, BindingFlags)
by name. Use the second parameter is needed, same is in the above item. - Check up if the value returned by
GetField
or GetProperty
is not Nothing
. If it is Nothing
, there is no such member, something is wrong. Consider we got field meta-data F
of the type FieldIndo
or property meta-data P
of the type PropertyIndo
. - For field, call
F.GetValue(Instance, Nothing)
; it will return required object O
. For a static field, both parameters are Nothing
. - For property, call
F.GetValue(Instance, Nothing)
; it will return required object O
. For a static field, both parameters are Nothing
. - You got an object
O
from GetValue
. Cast it to required type. For value types it will cause un-boxing. - PROFIT!
See:
http://msdn.microsoft.com/en-us/library/system.type.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx[
^].
I must say, this is a very bad way of using Reflection. Identification of anything by name is bad, because it's not good for support: should you misspell a name, a compiler won't detect the problem. One correct approach is using interfaces implemented in your classes or structures. With Reflection, you find out if requires interface is implemented, obtain a reference to interface instance and use it directly. No use of any string constants is needed.
[EDIT]
Don't get me wrong: Reflection based on type and member names is useful and important for serialization, including its advanced form
Data Contract, See
http://msdn.microsoft.com/en-us/library/ms733127.aspx[
^],
http://msdn.microsoft.com/en-us/library/ms730035.aspx[
^].
However, every time you hard-code meta-data names in your code as string constants, this is wrong approach.
—SA