Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner class and Outer class in c#

Tags:

c#

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 ?

like image 596
Thorin Oakenshield Avatar asked Jul 01 '10 04:07

Thorin Oakenshield


People also ask

What is inner class and outer class?

Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Syntax. Following is the syntax to write a nested class.

What is the difference between class and inner class?

A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.

What is the difference between inner class and nested class?

Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.


2 Answers

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.

like image 100
Dean Harding Avatar answered Oct 06 '22 23:10

Dean Harding


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);
        }
    }
like image 45
Arsen Mkrtchyan Avatar answered Oct 07 '22 00:10

Arsen Mkrtchyan