Say if I have a dropdown in a form and I have another nested class inside of this class .
Now what's the best way to access this dropdown from the nested class?
C# – What’s the best way of accessing field in the enclosing class from the nested class
cinner-classesnet
Related Topic
- C# – Catch multiple exceptions at once
- C# – How to use reflection to call a generic method
- C# – Case insensitive ‘Contains(string)’
- C# – How to update the GUI from another thread
- C# – Get int value from enum in C#
- C# – Try-catch speeding up the code
- Scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
Best Answer
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
Note that the InnerClass can access the "
s
" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "string s;
" isprivate
because no other access permission was specified.