Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Member Access from Nested Class to Containing Class [duplicate]

Tags:

c#

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!

like image 424
Mike Avatar asked Dec 17 '22 02:12

Mike


2 Answers

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.

like image 147
Adam Robinson Avatar answered Apr 30 '23 12:04

Adam Robinson


In ClassB's constructor pass an instance of class A.

like image 24
Matt Dearing Avatar answered Apr 30 '23 11:04

Matt Dearing