-1

I want to access some of the private members of a class which has its constructor defined as private. How do I create the PrivateObject for such class so that I can access its private members ?

I tried something like this but I cannot instantiate the class "MyClass1" so I am not able to instantite the PrivateObject.

    MyClass1 myClass = new MyClass1(); //gives compilation error
    PrivateObject po = new PrivateObject(myClass); //gives compilation error

Is there any workaround for this ?

krrishna
  • 2,050
  • 4
  • 47
  • 101
  • 1
    You probably shouldn't be doing this at all, but on the off chance you have a good reason, try getting the contructor via reflection: http://stackoverflow.com/a/3255716/424129 – 15ee8f99-57ff-4f92-890c-b56153 May 29 '15 at 17:13
  • 1
    You can only access private members of a class from inside the class itself. If you're not able to modify the class's source code, you can't change the private variables. – Benjamin Hodgson May 29 '15 at 17:13
  • 1
    @BenjaminHodgson PrivateObject is a type that does the necessary reflection work to access private members. See https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx – Brian Rasmussen May 29 '15 at 17:14
  • @BrianRasmussen, well, that's cheating ;) – Benjamin Hodgson May 29 '15 at 17:14
  • `var myClass = (MyClass1)Activator.CreateInstance(typeof(MyClass1), true);` – Habib May 29 '15 at 17:20

1 Answers1

0

Class with private constructor can only create itself from its own static method. For example:

class MyClass1
{
    private MyClass1()
    {

    }

    public static MyClass1 CreateInstance()
    {
        return new MyClass1();
    }
}

It's private members like fields or properties are always accessible only from inside of the class (unless you make some tricks with reflection). If the field is protected you can access it by deriving from this class. All other way it's by design created to restrict access to those fields and you should not try accessing them from the outside.

Edited: now I noticed you use PrivateObject class which is created to make reflection trickes mentioned above. So now you only need to create instance. You should check what is the designed way of initializing this object probably by some static method?

Or check this link for more hacks with reflaction and using Activator: http://www.ipreferjim.com/2011/08/c-instantiating-an-object-with-a-private-constructor/