what is a Constructor?
Constructor is a method that is called when an instance of an object is created.
They have the same name as a class.
Can a constructor have access modifier?
Yes. The following access modifiers are allowed
Public - This is called whenever a class is initialized.
Private - This will prevent the class from being instantiated(creating objects)
Protected - A protected member is accessible within its class and by derived class instances.
Internal - cannot be instantiated outside the assembly.
If a class has parametrized constructor, Do we need to have default constructor?
c# provides a default constructor with no parameters if there are no explicit ones. But if we have a parameterized constructor we need to specify a defualt one with no parameters.
what is static constructor?
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
Can constructors be inherited?
How can you call a base class constructor from a child class?
Child class can call base class constructor by using the keyword base.
In which order constructor is called in inheritance ?
If Class B inherits Class A ,when you create object of Class B then Class A constructor is called first then Class B constructor is called.
Console.WriteLine("i am class A");
Console.WriteLine("i am class B");
i am class A
i am class B
What is Copy constructor. Do you have this in C#?
c# does not provide copy constructor.
Can constructors be overloaded?
How do you overload a constructor?
Overload a constructor by specifying different parameters.
public numbers(int a)
How do you call one constructor from another in the same class ?
By using this keyword.
public numbers(int a):this()
When you create an object of the above class which constructor is called first ?
When you instantiate the above class first overloaded constructor is called and then the default one is called.
Can a constructor call itself by using this keyword?
No. it will through an compile time error.
Does memory gets allocated when constructor is called?
Yes using new operator.
What happens when you instantiate an object ?
When you create instance of a class using new operator, it does the following:
New memory is allocated
Instance is created on heap
Reference is created on stack and passed on the the instantiated object.
What happens if "new" keyword fails while instantiating?
It throws OutOfMemoryException.
What is default access modifier of constructor?
Is it Ok to throw an exception from a constructor?
No its not preferred. Constructors are used mainly for initialization purpose.but there are certain .Net Framewrok classes like DateTime,FileStream etc which throw exception from the constructor.