8

how to implement inner outer classes in c#

i have two nested classes

like

class Outer
{
    int TestVariable = 0;
    class Inner
    {
        int InnerTestVariable = TestVariable // Need to access the variable "TestVariable" here
    }
}

Its showing error while compiling.

It can be solved by

1) Making TestVariable as static

2) Passing an instance of Outer class to Inner class

but in java there is no need to create Instance or static .

can i use the same functionality in C# too ?

1

4 Answers 4

14

No, C# does not have the same semantics as Java in this case. You can either make TestVariable const, static, or pass an instance of Outer to the constructor of Inner as you already noted.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to access the private members of an Outer class from an Inner class that is nested within it, using a reference to an Outer instance, and I still get a CS1061 (".. does not contain a definition..").
3

You can create an instance of inner class without even have outer class instance, what should happen in that case you think? That's why you can't use it

Outer.Inner iner = new Outer.Inner(); // what will be InnerTestVariable value in this case? There is no instance of Outer class, and TestVariable can exist only in instance of Outer

Here is one of the ways to do it

  class Outer
    {
        internal int TestVariable=0;
        internal class Inner
        {
            public Inner(int testVariable)
            {
                InnerTestVariable = testVariable;
            }
           int InnerTestVariable; //Need to access the variabe "TestVariable" here
        }
        internal Inner CreateInner()
        {
            return new Inner(TestVariable);
        }
    }

Comments

0

Make variable internal or pass to inner's constructor

1 Comment

If i declare the variable as internal , it is not accessable inside the inner class
0

Short answer: No,

You will somehow need to inject the TestVariable into your Inner class. Making your testVariable could potentially lead to undesired behaviour. My sugestion would be to inject it via the constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.