1
class MainClass
    {
        public A APro { get; set; }
        public B BPro { get; set; }    
    }

class A
{
    public int ProA { get; set; }
}
class B
{
    public int ProB { get; set; }
}

Above shown is my structure (I have not mentioned the Access specifiers) My question is how to use class A and class B statically by using MainClass only which is also required to be a static class. Other than by any ways developer shouldn't use class A and class B. He/she must use MainClass to access class A and class B.

AK_
  • 7,981
  • 7
  • 46
  • 78
Kamlesh
  • 386
  • 1
  • 4
  • 19

2 Answers2

2

This is the answer you seek: https://stackoverflow.com/a/1665586/1413476

Answered by Ray Burns, one of the most creative pieces of code I've ever seen.

This will let only the containing class access the private child classes, This won't allow any outsiders from accessing the child classes.

Community
  • 1
  • 1
Erez Robinson
  • 794
  • 4
  • 9
1

Your answer is probably here: http://en.wikipedia.org/wiki/Software_design_pattern#Classification_and_list

I would just:

static class MainClass
{

    public static A APro { get; private set; }
    public static B BPro { get; private set; }    

    static MainClass()
    {
        A = new A();
        B = new B();
    }
}

class A
{
    internal A(){}
    public int ProA { get; set; }
}
class B
{
    internal B(){}
    public int ProB { get; set; }
}

I don't think you can do better in C# since you don't have friend classes. Also, it very much depends on what you are doing, but this is probably no the best design...

AK_
  • 7,981
  • 7
  • 46
  • 78
  • Yes, it is working. But my concern is "Other than by any ways developer shouldn't use class A and class B. He/she must use MainClass to access class A and class B." – Kamlesh Jun 23 '14 at 09:57
  • @Kamlesh what Erez suggests prevents it entirely, what I suggest prevents it from outside the assembly(dll)... – AK_ Jun 23 '14 at 10:40