Setting And Getting Private Variable Of A Class Without Properties

In this blog, you will learn how to access private members of class outside of scope is pretty easy.

Setting or getting private variable is quite a corner scenario while developing a new application and mainly developers will always find a way to access the private variable. But there is a direct way where we can access the private variable using reflection without much of hassle
 

What is the real-world scenario where I would need to access a private variable?

 
In real-world scenario I don’t you may ever need to access private variable in your own application. If you do then you’ll simply change it access specifier.
 
UTC or TDD development you might find yourself in scenario where you need to access or change the value of private variable of a class. In UTCs we often do such things to by check some negative scenario or for some other reasons.
 
Third party DLL or library, we may need to access private variable of a third-party variable
 
These are the cases where I need to access private variable
 

How could we achieve this?

 
Quite simple, you just need to do some R&D with reflection classes and need to spend some time with Type class provided in .net framework.
 
Example
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CrossProjectDemo  
  9. {  
  10.     public class Car : IEnumerable  
  11.     {  
  12.         private string name = string.Empty;  
  13.         private string prvtVariable = "PrivateVariable";  
  14.   
  15.         public string Name {  
  16.             get { return name; }  
  17.             set { name = value; }  
  18.         }  
  19.   
  20.     }  
  21. }  
As you can see there two private variables,
  1. name
  2. prvtVariable 
While name is being accessed in a public Property Name, prvtVariable will be accessed directly
 
Let’s see how,
 
First in your application import Reflection namespace
  1. using System.Reflection;  
Then follow the code,
  1. Car c = new Car();  
  2. Type typ = typeof(Car);  
  3. FieldInfo type = typ.GetField("prvtVariable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);  
  4. var value = type.GetValue(c);   
 
 
In the above image, you can see the type.IsPrivate is true which means the variable is private,
 
 
And we can access its value into the value variable.
 
That’s easy right.
 
Now, Let’s move towards how we can change its value. Lets’ make few changes to the existing code
 
Just add one-line right after Getvalue() method call,
  1. var value = type.GetValue(c);  
  2. type.SetValue(c, "Not so much");  
and now you have changed the value of a private variable,
 
 
Easy, isn’t it. So here we’re accessing private variables through reflection.
 
For more detail info like this visit this.
 
Thanks