Friday, January 15, 2010

Questions and Answers on Constructors and Destructors in C#

Constructors
Is the Constructor mandatory for the class ?
Yes, It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier.

What if I do not write the constructor ?
In such case the compiler will try to supply the no parameter constructor for your class behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor ( with or without parameters), then compiler will not make any such attempt.

What if I have the constructor public myDerivedClass() but not the public myBaseClass() ?
It will raise an error. If either the no parameter constructor is absent or it is in-accessible ( say it is private ), it will raise an error.

Can we access static members from the non-static ( normal ) constructors ?
Yes, We can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.

How can one constructor call another?
To call one C# constructor from another, before the body of the constructor, use either:
: base (parameters)
: this (parameters)
Example :
public class mySampleClass
{
public mySampleClass(): this(10)
{
}
public mySampleClass(int Age)
{
}
}


Are C# constructors inherited?
No. C# constructors cannot be inherited. If constructor inheritance were allowed, then necessary initialization in a base class constructor might easily be omitted. This could cause serious problems which would be difficult to track down. For example, if a new version of a base class appears with a new constructor, your class would get a new constructor automatically. This could be catastrophic.

How call a virtual method from a constructor or destructor?
The C# compiler inserts a call to the base class constructor at the beginning of any derived constructor in order to maintain OO semantics, i.e. that the base class constructor is called first. In a similar fashion, when C# destructors call virtual methods, virtual method calls from a base destructor are directed to the derived implementation. Therefore, in C#, a virtual method can be called from a constructor or destructor. But, usually, it is a bad idea.

What is the syntax for calling an overloaded constructor from within a constructor?
We can not use this() and constructor-name(). It gives a compile time error.
The syntax for calling another constructor is as follows:

class A
{
A (int i) { }
}

class B : A
{
B() : base (10) // call base constructor A(10)
{ }

B(int i) : this() // call B()
{ }

public static void Main() {}
}

Why must struct constructors have at least one argument?
The .NET Common Language Runtime (CLR) does not guarantee that parameterless constructors will be called. If structs were permitted to have default, parameterless constructors, the implication would be that default constructors would always be called. Yet, the CLR makes no such guarantee.

For instance, an array of value types will be initialized to the initial values of its members—i.e., zero for number type primitive members, null for reference types, and so forth—and not to the values provided in a default constructor. This feature makes structs perform better; because, constructor code need not be called.

So, requiring that a constructor contain a minimum of one parameter reduces the possibility that a constructor will be defined which is expected to be called every time the struct type is built.

C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

If I have a constructor with a parameter, do I need to explicitly create a default constructor?
Yes

Can I call a virtual method from a constructor/destructor?
Yes, but it's generally not a good idea.In .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)

The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

What are static constructors?
This is a new concept introduced in C#. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
The syntax of writing the static constructors :

public class myClass
{
static myClass()
{
}
}

Does a static constructor have a access modifier?
There should be no access modifier in static constructor definition. to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it

Can a static constructors have parameters?
The static constructor should be without parameters. is going to be called by CLR, who can pass the parameters to it, if required, No one, so we cannot have parameterized static constructor.

How will you access non static members of a class from your static constructor?
Non-static members in the class are specific to the object instance so static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.

Can you overload a static constructor?
Overloading needs the two methods to be different in terms to methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.

Is this code valid then?
public class myClass
{
static myClass()
{
public myClass()
{
}
}
}
This is perfectly valid.Because the time of execution of the two method are different. One is at the time of loading the assembly and one is at the time of object creation.

What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Does C# provide copy constructor?
No, C# does not provide copy constructor.

If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Destructors
How do destructors work in C#?
A destructor is a method that is called when an object is destroyed—it's memory is marked unused. C++ destructors are used to free up memory and other resources and to perform housekeeping tasks. In .NET, the Garbage Collector (GC) performs much of this type of work automatically. Generally, rather than define a destructor for manual cleanup, let the Common Language Runtime (CLR) handle it.

In C#, the Finalize method performs the operations that a standard C++ destructor might perform. Finalizers are similar to destructors except that it is not guranteed that they will be called by the CLR.

Here is a sample finalizer specification using the C++ destructor syntax which places a tilde (~) symbol before the class name:

class Test
{
~Test()
{
...
}

public static void Main() {}
}When defining a C# finalizer, it is not named Finalize. However, finalizers do override object.Finalize(), which is called during the garbage collection process.

How make a C# destructor virtual?
By definition, a C# destructor is virtual. Because, a C# destructor is basically an override of the Finalize method of System.Object. Therefore, these is no need to make a C# destructor virtual.