Is it Possible to expose a private variable in c# ?

2.2k views Asked by At

i just wanted to know Is it Possible to expose a private variable in c# ? I know if data of a class is private means is not accessible from outside class. if, yes, then how ?

3

There are 3 answers

6
Sergey Berezovskiy On BEST ANSWER

It is possible. Use Reflection for that:

Type type = yourObj.GetType();
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
FieldInfo field = type.GetField("fieldName", flags);
object value = field.GetValue(yourObj);

Reflection allows to read type's metadata at runtime and uncover types internals (fields, propertis etc).

0
Chandan Kumar On

Many more Thanks @Sergey Berezovskiy .

Here i have solved with the help of that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ExposePrivateVariablesUsingReflection
{
    class Program
    {
        private class MyPrivateClass
        {
            private string MyPrivateFunc(string message)
            {
                return message + "Yes";
            }
        }

        static void Main(string[] args)
        {
            var mpc = new MyPrivateClass();
            Type type = mpc.GetType();

            var output = (string)type.InvokeMember("MyPrivateFunc",
                                        BindingFlags.Instance | BindingFlags.InvokeMethod |
                                        BindingFlags.NonPublic, null, mpc,
                                        new object[] {"Is Exposed private Member ? "});

            Console.WriteLine("Output : " + output);
            Console.ReadLine();
        }
    }
}
0
Jani Hyytiäinen On

You could use reflection to access private variables. However, even though a bit off-topic, I wanted to share something regarding InternalsVisibleTo.

Let's say you have your Domain Objects in an assembly MyExample.DomainObjects and you don't want to put the setters public but you need your service layer to be able to write to them but it is in a separate assembly, you could still use internal setters and avoid reflection:

namespace MyExample.DomainObjects {
    public class MyObject{
        public string MyProp { get; internal set; }
    }
}

You could have your MyExample.ServiceLayer in a separate assembly if you put the following in the MyExample.DomainObjects project's AssemblyInfo.cs

[assembly: InternalsVisibleTo("MyExample.ServiceLayer")]

Then you can call the internal setters in MyExample.DomainObjects from MyExample.ServiceLayer.