CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Sep 2001
    Location
    Turkey
    Posts
    173

    access to outer class from inner class

    Is there a smart way to access any attribute/function of outer class from the inner class? This is a very intelligent property of Java , I don't know whether C# offer such a way that is similar with Java or not. Any idea? i wrapped a Java example below. Thanks...

    (*) I know that the straightforward solution is to use home-pattern like defining

    Code:
    class Inner
    {
         Inner( Outer home ); // get it from constructor
    }
    But, I don't want to use home pattern!... Here is the Java-way:

    Code:
    public class Outer
    {
        class Inner
        {
            int innerMember;
    
            void DoSomething()
            {
                innerMember = Outer.this.outerMember;
            }
        }
    
        public int outerMember = 1;
    
        public void Go()
        {
            Inner inner = new Inner();
            inner.DoSomething();
        }
    
        public static void main( String[] args )
        {
            Outer outer = new Outer();
            outer.Go();
        }
    }

  2. #2
    Join Date
    May 2003
    Location
    Germany
    Posts
    936

    Re: access to outer class from inner class

    Hm, what do you do if your inner class is inside of two different classes? Which is outer? I think it is a bad design. Use the home pattern and you will get good code. Where is the problem?
    Useful or not? Rate my posting. Thanks.

  3. #3
    Join Date
    Sep 2001
    Location
    Turkey
    Posts
    173

    Re: access to outer class from inner class

    By definition, an inner class can be in only one outer class.
    What do you mean by the comment:
    what do you do if your inner class is inside of two different classes?

  4. #4
    Join Date
    May 2003
    Location
    Germany
    Posts
    936

    Re: access to outer class from inner class

    Sorry, I misread you code. My mistake. Now I saw that you wrote nested classes. Forget what I said about two different classes. But forthermore I think it is a bad design. Anyone tries to write modular code, why do you want to write nested code?
    Give me an example for what this should be good?
    Useful or not? Rate my posting. Thanks.

  5. #5
    Join Date
    Apr 2005
    Location
    Norway
    Posts
    3,934

    Re: access to outer class from inner class

    Well, looking at Compiler Error CS0038, I don't think it is possible. It says:

    Cannot access a nonstatic member of outer type 'type1' via nested type 'type2'

    A field in a class is not automatically available to a nested class. To be available to a nested class, the field must be static. Otherwise, you must create an instance of the outer class.
    - petter

  6. #6
    Join Date
    May 2005
    Location
    Oregon
    Posts
    3,725

    Lightbulb Re: access to outer class from inner class

    I think you are looking for something like Conainment and aggregation.
    have alook on this in MSDN.
    ms-

    help://MS.MSDNQTR.2003OCT.1033/cpguide/html/cpconInheritanceAggregationContainment.htm

  7. #7
    Join Date
    Dec 2003
    Location
    http://map.search.ch/zuerich.en.html
    Posts
    1,074

    Re: access to outer class from inner class

    C# only supports the java notion of a "static nested class". The only way to get what you want is to use the "home pattern".
    Useful? Then click on (Rate This Post) at the top of this post.

  8. #8
    Join Date
    Apr 2005
    Posts
    576

    Re: access to outer class from inner class

    Quote Originally Posted by the one
    By definition, an inner class can be in only one outer class.
    This is not correct, at least not in c#, you can create an instance of an inner class without having an instance of the outer class. In fact, the outer and inner classes may have any relations that any other two classes have (none, 1-1, 0..1-1, 1-n etc.)

    So norfy is correct, the only way to go is to use the home pattern.

    Quote Originally Posted by torrud
    Give me an example for what this should be good?
    Inner classes can be useful where a class is needed only by one class or is very closely related to one class.

    Typically iterators are inner classes.

    I sometimes implement the state pattern using inner classes for the different states.

  9. #9
    Join Date
    Sep 2001
    Location
    Turkey
    Posts
    173

    Re: access to outer class from inner class

    I understand your comments. I shuld thank you for your interest. I still wanted to reply to explain why this kind of usage would be usefull. Firstly I should introduce some facts and then i will try to do inferences.

    -Any inner (nested) class can be accesed only by the outer class.
    -Any inner (nested) class can be instantiated only by the outer (home).
    -Any instance of inner class has a life cycle which is shorter than or equal to the outer (home) instance.
    -Life cycle of outer instance exactly covers the life of inner instance.

    Therefore the above facts conclude that:
    - the inner class is a natural part of the outer class. but still it is designed as a separate(?) class to reach more modularity or some specific behaviours. I mean it is very straightforward/default/common/natural to use the pointer of outer instance (Outer.this.someProperty) inside the inner class. We don't have to use it, but it is very common. Therefore Java, had been introduced such a flexibility. Anyway, we can use home-pattern and mimic it in C#. However please be aware that this means more lines of code and complexity....

    I want to also introduce an example:
    -Assume that we will assign some actions to the toolbar buttons. The desired actions will inherits almost all properties, fucntions, etc from the base except a specific one. ( an abstract function like "void PerformAction" )... see the story:

    a very common resusable base class implemented in a library

    Code:
    public abstract class ActionBase
    {
        // action name, text, description, tooltip, icon, rule, visibility, etc are all implemented...
    
         public abstract void PerformAction(); // override it in your child classes...
    }
    my specific class MyMainFrame

    Code:
    public class MyMainFrame : Form
    {
        void InitAll()
         {
               // create tool bar... 
               // insert some buttons to the toolbar
               // assign actions to the buttons like "Add X", "Delete X", "List Xs"...
               // which is very specific and it is higly dependent to the status of
               // some GUI controls on this form. ( like a selected node of treeview 
              // located in the left panel of this form. )
              // the actions are defined... and PerformAction should be implemented.
              // write inner classes... // see below
              AddXToTheLeftTreeAction action1 = new AddXToTheLeftTreeAction();
               ((MyToolBarButton)(toolBar.buttons[x])).AddAction( action1 );
                        
    
         }
    
         class AddXToTheLeftTreeAction : ActionBase
         {
                 // constructor
                 AddXToTheLeftTreeAction() : base( text1, text2, text3, icon1, icon2, rule )
                 {
                             // some code
                 }
                  
                  public override PerformAction()
                  {
                            MyMainFrame.this.leftTree.Add( "root", new SomeObj() );
                            // ...                        
                  }
         }
    }


    Possibly I couldn't explain the usefull cases but Java coders will understand me. Anyway.. still thanks..

  10. #10
    Join Date
    Apr 2005
    Posts
    576

    Re: access to outer class from inner class

    Quote Originally Posted by the one
    -Any inner (nested) class can be accesed only by the outer class.
    -Any inner (nested) class can be instantiated only by the outer (home).
    -Any instance of inner class has a life cycle which is shorter than or equal to the outer (home) instance.
    -Life cycle of outer instance exactly covers the life of inner instance.
    This is not true in c#, an inner class (or nested type which is the proper term in c# - I just found this out when I searched the MSDN documentation for it), can be public and thus it can be accessed and instantiated by any other object, and the life cycles of the inner and outer instances have nothing special to do with each other.

    See for instance c# language specification, section 10.2.6.4:

    A nested type and its containing type do not have a special relationship with regard to this-access (Section 7.5.7). Specifically, this within a nested type cannot be used to refer to instance members of the containing type. In cases where a nested type needs access to the instance members of its containing type, access can be provided by providing the this for the instance of the containing type as a constructor argument for the nested type.

    ("Providing the this for the instance of the containing type..." refers to the Home pattern described in the beginning of this thread by the one.)

    As far as I can see, the main difference between inner types and other types in c# is that inner types has access to private and protected members of the containing type.

    So I guess inner types are a bit different in c# compared to Java (but I have not been programming in Java for the last 9 years).

    Still, I find inner types useful, the examples I gave earlier (State and Iterator) are typical uses of inner classes where the inner class needs access to private members, not using inner classes would mean that the contained class needs to change access of some members to internal.

    And, in most cases (certainly in every case where I have used inner classes), the inner class is created from the outer class (e.g. an Iterator is created via an GetEnumerator method, states are typically private etc.).

  11. #11
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: access to outer class from inner class

    It seems to me that every you are dancing around the core of the answer without noticing it (klintan was the most close one).

    Nested types (classes) in C# are only about the scope. The have different string name - Namespace.OuterClass+NestedClass. The outer class is here in role of namespace. And can access private members of the outer class.

    There is (or better has not to be) any relation between outer and nested class in terms of object model. Nothing like aggregation which I feel in the Java's construct. You can have instance of nested class without any instance of outer class and vice versa.

    So its true that others have said: use home pattern. And I think that nested classes are not neccessary here.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured