Wednesday, March 4, 2015

10 important C# Constructor and destructor interview questions

Is it possible that one class have more than one constructor?

Yes, considering each one of them have different function signature.

Does every have class have constructors? Or I want to ask is it possible to create a class without constructor?
No, every class will have default constructor (constructor with no parameter) defined. 

If it is already defined, what happens when we create our own?
The default one will be replaced.

Let say I have class and I have create a new constructor into it accepting 2 parameters. So many constructors does my class have now?
Only one, because as soon as we create new constructor in the class default one will get removed automatically. After that we left with only one constructor and that is parameterized constructor. Now if want we can also create one more constructor with no parameters.

Is it is possible to make Constructor private? If yes why? If no Why? 
Yes it can be declared as private/protected/internal other as public. We normally do that we want to restrict other classes from creating object of the class directly.

When we create the object of the class constructor will get invoked, what happen if we go and create the object of derived class?
First constructor of base class get invoked and the constructor of derived class get invoked,

How it different from destructors?
Constructors get called automatically when object of the class get initialized and main purpose of constructor is initialization of class members.
Whereas destructors get invoked when life of an object ends. Main purpose of destructor is cleaning class resources (unmanaged resources).


Is it possible to make constructor static?
Yes. It will be invoked when first time class get used (Object get initialized or static member get accessed)


Can we inherit from a class having private constructor ?
We cannot inherit from classes that are having private constructors. The reason is suppose if you are inheriting from a base class which has only private constructors and if you create an object for the derived class then the base class constructor will be called. Because the base class contains only private constructors and due to ‘private’ access modifier it is not accessible from the derived class. So it will give you an error with a syntax as follows ‘Error 1 ’ConsoleApplication45.Program.Program()’ is inaccessible due to its protection level’.

No comments:

Post a Comment