I have three classes like this.
class A { public class innerB { //Do something } public class innerC { //trying to access objB here directly or indirectly over here. //I dont have to create an object of innerB, but to access the object created by A //i.e. innerB objInnerB = objB; //not like this innerB objInnerB= new innerB(); } private innerB objB{get;set;} **//Private** public A() { objB= new innerB(); } }
I want to access the object of class B in Class C that is created by class A. Is it possible somehow to make changes on object of Class A in Class C. Can i get Class A's object by creating event or anyhow.
Edit: My mistake in asking the question above. Object of B created in A is private not public
IS IT POSSIBLE TO DO THIS BY CREATING EVENT
If anyhow I become able to raise an event that can be handled by Class A, then my problem can be solved.
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.
Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.
The inner class can access any non-static member that has been declared in the outer class. Scope of a nested class is limited by the scope of its (outer) enclosing class. If nothing is specified, the nested class is private (default). Any class can be inherited into another class in C# (including a nested class).
You need to pass a reference of OuterClass
to InnerClass
, perhaps in the constructor, like:
public class OuterClass { //OuterClass methods public class InnerClass { private OuterClass _outer; public InnerClass(OuterClass outer) { _outer = outer; } } }
Then you can use that reference in all of your InnerClass
methods.
If I'm reading you correctly you want to access the objB property of class A within innerC WITHOUT passing it along.
This isn't how C# inner classes work, as described in this article: C# nested classes are like C++ nested classes, not Java inner classes
If you want to access A.objB from innerC then you are going to have to somehow pass class A to innerC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With