1

In Java, if two classes are defined inside one top-level class, they have access to each other's private members (fields, constructors, methods). So in a situation like the following you could use all of the private members of ClassA inside ClassB, and vice-versa.

public class TopLevelClass {

     private static class ClassA {
         // Code omitted
     }

     private static class ClassB {
         // Code omitted
     }
 }

Can you do anything similar in C#?

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116

1 Answers1

2

Even with nested classes in C#, two separate (not nested within each other) classes cannot access each other's private members (even though they share a parent). They can however access private members of the parent class.

You can get access to private members using reflection if you really need to, though of course, if you need access to them they probably shouldn't be private in the first place.

See Nested Types for more info.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Thank you. I thought that was the answer - I just wanted confirmation. One approach I find really useful in Java is to write helper classes that are only of use to the top-level class they're defined in. For these classes I can just make everything private and don't need to worry about writing accessor methods. – Paul Boddington Dec 10 '14 at 21:41
  • @pbabcdefp There are always auto-properties :) – BradleyDotNET Dec 10 '14 at 21:43