How can you prevent the class from being inherited by other classes without using "Sealed" keyword.?

 Posted by Nagasundar_Tn on 11/27/2012 | Category: C# Interview questions | Views: 7557 | Points: 40
Answer:

By declaring base class constructor as Private we can avoid that class being inherited by another class. When we create the object for the derived class the base class constructor called automatically and executed. Hereit cannot be executed due to its protection level. See the code snippet:

namespace Example

{
class Base
{
private Base()
{
}
public void Test()
{
Console.WriteLine("Test");
}
}
class Program : Base
{
static void Main(string[] args)
{
Program pObj = new Program();
pObj.Test();
}
}
}
If we run the above code we get the following error :

'Example.Base.Base()' is inaccessible due to its protection level'


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response