1

I have the following code:

public ClassC 
{
    public class ClassA extends ClassB<T> 
    {
        /**
        * @uml.property  name="index"
        */
        private int index;
        public ClassA()
        {
            super(ClassC.this);
            index = 0;
        }
    }

I have found that, ClassName.this is needed from inner classes to get to the outer class instance of this, but it doesn't help me much. I know my issue is about lack of knowledge but some shorter explanation will save me some time. How this should look in c#? I have renamed classes just to make it a more general question.

Ben
  • 2,433
  • 5
  • 39
  • 69
David
  • 127
  • 2
  • 9
  • Might have something to do with your nested classes... – BradleyDotNET May 04 '15 at 22:48
  • 1
    In c#, you should not need nested classes of any kind about 99.5 percent of the time. – Robert Harvey May 04 '15 at 22:49
  • 1
    @RobertHarvey 0.05% sounds a bit high :) – BradleyDotNET May 04 '15 at 22:50
  • 1
    @RobertHarvey true for *public* classes, nested private classes are quite useful. – Alex May 04 '15 at 22:51
  • 1
    @alex: My percentage still applies. Note the use of the words "of any kind" in my original comment. If you have a valid example, I'm all ears, but usually nested classes are an indication that your class is doing too much. – Robert Harvey May 04 '15 at 22:51
  • I have to re-write a more complex project from java to c# which was obviously not written by me. – David May 04 '15 at 22:53
  • 1
    Just use composition instead, and write all of the required classes in the same namespace, not nested. – Robert Harvey May 04 '15 at 22:53
  • @RobertHarvey, the percentage may indeed hold true. I am talking specifically about private inner classes implementing an interface or abstract base class, although this may be opinion based. Refer e.g. to [Private inner classes in C# - why aren't they used more often?](http://stackoverflow.com/questions/454218/private-inner-classes-in-c-sharp-why-arent-they-used-more-often). – Alex May 04 '15 at 22:59
  • @Alex: What Jon Skeet is basically saying there is that `MyCleverEnum` will only be used in that one class, and not anywhere else in the program, or in any other program for that matter. It can happen that way, but in my experience well-written classes like that should be made public standalone classes, so that the rest of the program can also make use of them. – Robert Harvey May 04 '15 at 23:02

1 Answers1

2

From documentation:

The nested, or inner type can access the containing, or outer type. To access the containing type, pass it as a constructor to the nested type. For example:

public class Container
{
    public class Nested
    {
        private Container parent;

        public Nested()
        {
        }
        public Nested(Container parent)
        {
            this.parent = parent;
        }
    }
}
MChaker
  • 2,610
  • 2
  • 22
  • 38