Constructor: Is
like a function without return type, its name must be same as class name.
Q1. How many type of constructor are there
in C#?
1.
System defined default constructor - > when
user does not define constructor then compile implicitly provides default
constructor.
2.
User defined constructor -> when user
explicitly provides constructor. After that implicit default constructor will
not be loaded, if needed then have to define explicitly.
3.
User Defined Parameterized constructor ->
constructor with argument ex. SqlConnection(string conStr)
4.
Static, public, private, protected, internal
etc.
Q2. What is constructor chaining?
When we call constructor with new keyword and try to create
object of class then it first it go to super class constructor to initialise
super class first and then it come to initialise calling constructor’s class.
See example of Q4.
Q3. How to pass data to base class?
Through BASE keyword, see example of Q4
Q4. What is overloaded constructor?
More than one constructor in a class is known as overloaded
constructor. See example of Q4
Q5. What is static Constructor?
Constructor with static keyword,
It will be called only once during program’s lifecycle, when
first object of class will be created
It cannot have access modifier and
Only one static constructor a class can have.
Q6. What will be the O/P of programs?
public class A
{
public
A()
{
Console.WriteLine("A");
}
}
public class B:A
{
public
B()
{
Console.WriteLine("B");
}
}
class Program
{
static void Main(string[]
args)
{
B
objB = new B();
Console.WriteLine("C");
Console.ReadKey();
}
}
|
public class
A
{
static
A() // this static constructor will called only once
{
Console.WriteLine("A");
}
public
A(int x)
{
Console.WriteLine("A1");
}
}
public class B : A
{
public
B():base(1)
{
Console.WriteLine("B");
}
}
class Program
{
static
void Main(string[]
args)
{
B
objB = new B();
Console.WriteLine("C");
Console.ReadKey();
}
}
|
public class B
{
private
B()
{
Console.WriteLine("B");
}
}
class Program
{
static
void Main(string[]
args)
{
B
objB = new B();
Console.WriteLine("C");
Console.ReadKey();
}
}
|
public class B
{
public
static B()
{
Console.WriteLine("B");
}
}
class Program
{
static
void Main(string[]
args)
{
B
objB = new B();
Console.WriteLine("C");
Console.ReadKey();
}
}
|
No comments:
Post a Comment