Thursday, 10 October 2019

Setting and getting private variable of a class without properties



Setting or getting private variable is quite a corner scenario while developing a new application and mainly developer 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-
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrossProjectDemo
{
    public class Car
    {
        private string name = string.Empty;
        private string prvtVariable = "PrivateVariable";

        public string Name {
            get { return name; }
            set { name = value; }
        }

        public Car()
        {
        
        }
    }
}

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
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);



In above image you can see that the type.IsPrivate is true which means 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

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 more detail info like this visit this
Thanks

1 comment:

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...