This article reflect on how to access private member of class. There are multiple routes to achieve this but in this article we will focus on the right approach.
Introduction
Setting or getting private variable is quite a corner scenario while developing new application. Developers always find a work around to make the data available in private member to them. However, There is a more efficient and recommended mechanism to access private member. Here we can access the private variable using reflection and in built microsoft libraries.
Real-world scenario where access private member is required?
In real-world, it is possible that you never encounter such scenario where there is a need to access private variable. Nevertheless, If you do then you’ll simply change access specifier for the member.
In 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 re-create negative scenario. We might need to access private variable of a third-party variable to generate desirable result.
How can we access private member of class?
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 .
Example
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CrossProjectDemo
{
public class Car : IEnumerable
{
private string name = string.Empty;
private string prvtVariable = "PrivateVariable";
public string Name {
get { return name; }
set { name = value; }
}
}
}
As you can see, here are two private variables,
- name
- 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
using System.Reflection;
Then follow the code,
Car c = new Car();
Type typ = typeof(Car);
FieldInfo type = typ.GetField("prvtVariable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var value = type.GetValue(c);
C#Copy
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.
Write to private member
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,
var value = type.GetValue(c);
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 details on reflection visit microsoft learner site here. Cheers!!!
More posts like this
- Introduction to Azure Cosmos DB
- Enhancing app security with Azure Managed Identities
- IL code performance of Generic List And Non Generic List
- How does a dictionary maintains data
- What is better between Enumerator or foreach