Click here to Skip to main content
16,014,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is it possible to access non-public methods of a nested class? I need to restrict the ability to initialize a special class (the nested class) to the class that the special class in nested in.
Posted

Yes, actually you could do everything with reflection. First, place
using System.Reflection; 

Second, get the type of the class
Type t = MyClass.InnerClass.GetType()

Third, play around with that type (it will give a collection of public and non-public members)
t.GetMethods()[0].Invoke(this)

I'm really not sure about the exact syntax but if you're using Visual Studio, that should not be a problem.
 
Share this answer
 
If you want only a specific type of a family of types, you can send the type in the constructor.

public B(object caller)
{
   if(caller is A) //or caller is IA (IA is interface)
     throw new NotSupportedException("Object of A is not supported");
}


Something like this :thumbsup:
 
Share this answer
 
Comments
CaptainSeeSharp 11-Sep-10 16:13pm    
Thank you, however I thought of a different design that doesn't require what I needed.
What does it mean by
"I need to restrict the ability to initialize a special class"

You can only do so using a private constructor. It will be a singleton pattern in your case.

C#
public class A
   {
       public A()
       {
           B b1 = B.GetObject();
       }
       public class B
       {
           private B()
           {
           }
           public static B GetObject()
           {
               return new B();
           }
       }
   }


Is it what you needed ?
 
Share this answer
 
Comments
CaptainSeeSharp 11-Sep-10 12:58pm    
No that's not what I need. I need to restrict initialization of class B to class A while still making class B public.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900