Can a nested class access the outer class? Give an example?

 Posted by Tripati_tutu on 11/16/2010 | Category: C# Interview questions | Views: 3651 | Points: 40
Answer:

Yes, the nested class or inner class can access the outer class. Nested types can access private and protected members of the containing type, including inherited private or protected members.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nested
{
class ClsContainer
{
string outerClsVariable = "This is outer class variable";

public class InnerClass
{
ClsContainer Obj = new ClsContainer();
string innerClsVariable = "This is inner class variable";

public InnerClass()
{
Console.WriteLine(Obj.outerClsVariable);
Console.WriteLine(this.innerClsVariable);
}
}
}

class Exec
{
public static void Main()
{
ClsContainer.InnerClass nestedClsObj = new ClsContainer.InnerClass();
}
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response