Is it possible to create an object of an inner class in the constructor of an outer class in 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 link from the link below: Is it possible to create an object of the inner class in the constructor of the outer class?
My colleague said that this is not possible in C #, and it is completely illegal. Please guide me.
Perhaps if you declare an Inner public class
public class Inner { }
The problem with your code is how the calling code knows what Inner obj is, since it is not available outside the outer class.
, . .
public class Outer { public Outer(IInner inner) { } } public class Inner: IInner { } public Interface IInner { }
Of course it is possible. Technically, there is nothing wrong with your code (if you make your inner publication or your outer class inner).
Please note, however, that it is not recommended to use publicly available nested classes, see this question for details:
This is illegal (leading to a compiler error), not Inneryet public.
Inner
public
After designating it as public, it is absolutely legal.