Thursday, August 25, 2011

C# and .Net Interview Question:- What are InnerClass and how to use them?

InnerClass: - A class which is declared inside the body of another class is called as InnerClass.

Syntax: -

class Outer

{

//having it's own implementation.

class inner

{

//having its own implementation

}

}
Note:-
1. An inner class can access the static members of the containing outer class
without using that class name.

2. Another difference is when the inner class accesses an instance of the outer
class; it can access that object's private members even if they are not static.

There are many reasons to use InnerClass but the two important reasons are as
follows.

1. Organizing code into real world situations where there is a special
relationship between two objects.

2. Hiding a class within another class so that you do not want the inner class
to be used from outside of the class it is created within.

Let’s see small demonstration on how exactly InnerClass is declared or created.
Step1: - Create a new Project for that Go To > File > New > Project > Windows > Console Application.





Step2: - Create an inner class like below code snippet.

class MyClass

{

public void Method1()

{

Console.WriteLine("I am the MainClass");

}

class InnerClass1

{

public void Method1()

{

Console.WriteLine("I am the InnerClass");

}

}

}


The class InnerClass1 here is enclosed inside the declaration of class MyClass. InnerClass1 is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than MyClass’s scope.
Step3: - let’s see how we access the above two classes in the main class.

static void Main(string[] args)

{

MyClass obj = new MyClass();

obj.Method1();

MyClass.InnerClass1 obj1 = new MyClass.InnerClass1();

obj1.Method1();

Console.ReadLine();

}

In the above code snippet you can see that in order to use the inner class I have created the instance like below code snippet.

MyClass.InnerClass1 obj1 = new MyClass.InnerClass1();



Now when you run your application you will see result like below diagram.



Also have a look on this video, which is asked in most of the interviews.


Please click here to see more C#/Dotnet interview questions

Regards,

Visit Authors blog for more Most asked Dotnet interview questions


No comments: