I have ClassB, which is nested inside of ClassA. In ClassA I have a variable called _MyId... how can I access _MyId from ClassB?
Thanks in advance!
Put simply, you'll need a reference to an instance ClassA
within ClassB
.
C#'s nested classes work differently from Java's, if that's what you're used to. The closest analog would be Java's static class
when applied to a nested type (meaning that C#'s nested classes are not associated with a particular instance of the outer class).
In other words, C#'s nested classes are not "special" when compared to outer classes, other than the fact that they have visibility into the private members of the outer class. Nonetheless, you still need a reference to the outer class in order to access them.
If the field is static
, you can simply refer to it as ClassA._MyId
. If it's not you should use classAInstance._MyId
where classAInstance
is an instance of ClassA
.
If you're coming from Java background, you should note that nested classes in C# are similar to static nested classes in Java.
You have to refer to a particular instance of ClassA
in order to retrieve a member. If your instance is called foo
, just use foo._MyId
.
If _MyId is static you can access it by it's name or as ClassA._MyId.
But otherwise you need an instance of ClassA first, and there is little difference with acces from another class (that is not nested). But members from ClassB do gain access to private members of ClassA.
Explanation: Nesting classes is a static relation between the 2 Types, there is no implicit relation between instances. You will have to pass references to objects between them just as if the classes were not nested.