3

Can we create an object of the inner class in the constructor of the outer class into C#? Is it legal?

public class Outer
{
    public Inner InnerObj {get; set; }

    public Outer()
    {
        Inner inner = new Inner();
    }

    public Outer(Inner inner)
    {
        InnerObj = inner;
    }

    public class Inner
    {
    }
} 

for Java I take the reference from below link: Can we create an object of the inner class in the constructor of the outer class?

My colleague said this is not possible in C# and it's totally illegal. Please guide me.

3
  • 1
    You should listen to the compiler, not your colleague and for such a trivial matter probably not us. It's not difficult to see that it compiles just fine. Commented Apr 25, 2012 at 8:07
  • I tried it, I am not getting any error, but my colleague said it's not Object-Oriented and totally illegal Commented Apr 25, 2012 at 8:08
  • Does (s)he think you'll go to prison (aha-ha-ha)... I think your colleague might need to be kicked upstairs Commented Apr 25, 2012 at 8:54

4 Answers 4

2

It is possible if you declare the Inner class public

public class Inner { }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, my inner class is public class.
1

The problem with your code is how does the calling code know what Inner obj is as it is not accessible outside of the outer class.

A better design would be to have the inner class outside of the outer class so that its not so tightly coupled. Also pass the object against an interface.

public class Outer
{        
    public Outer(IInner inner)
    {

    }
}

public class Inner: IInner
{
}

public Interface IInner
{
}

Comments

1

Sure, it's possible. Technically, there is nothing wrong with your code (if you make your inner public or your outer class internal).

Note, however, that this is not recommended to use public nested classes, see this question for details:

Comments

0

That's illegal (leads to compiler error) until Inner is not public.

After marking as public it's absolutely legal.

2 Comments

Inner class in public class. Now is it illegal.
@sarooptrivedi: Now everything is fine. The same exists in FCL itself, e.g. Dictionary<K,V>+KeyCollection (you can check it out using Reflector)

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.