Constructor Interview Questions C#.NET 

Constructor Interview Questions C#.NET

In this article, I am going to discuss most frequently asked Constructor Interview Questions and Answers on C#.NET. To understand the below questions and answers first have a look at the below two articles where we discussed the Constructor and Destructor in details.

The Constructor in C#

The Destructor in C#

What is a constructor?

Constructors are the special types of methods of a class which get executed when its object is created. Constructors are responsible for object initialization and memory allocation of its class and new keyword role is creating the object.

Explain the different rules of a constructor.
  1. Constructor name should be same as class name.
  2. It should not contain return type even void also.
  3. It should not contain modifiers.
  4. In its logic return statement with value is not allowed.

NOTE:

  1. It can have all five accessibility modifier.
  2. The Constructor can have parameters.
  3. It can have throws clause it means we can throw an exception from a constructor.
  4. The Constructor can have logic, as part of logic it can have all C#.NET legal statements except return statement with value.
  5. We can place return; in a constructor.

Can we define a method with the same class name?

No, it is not allowed to define a method with the same class name. It will give compile time error.

How many types of constructors are there in C#.net?
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

Explain about Default constructor?

Constructor without parameter is called as default constructor. Again default constructor is classified into two types.

  1. System-defined default constructor
  2. User-defined default constructor
Explain about system-defined default constructor?

If as a programmer we are not defined any constructor explicitly then the system will provide one constructor at the time of compilation and that constructor is called as system-defined default constructor and that constructor will assign default values to the data fields (non-static variables).

As this constructor is created by the system this is also called as system-defined default constructor.

The system will provide the default constructor only if as a programmer we are not defined any constructor explicitly.

When must developer provide the constructor explicitly?

If we want to execute some logic at the time of object creation, that logic may be object initialization logic or some other useful logic, the developer must provide the constructor explicitly.

Explain about user-defined default constructor?

The constructor which is defined by the developer without any parameter is called as user-defined default constructor.

This constructor does not accept any argument but we can write logic in its body.

The drawback of the default constructor is every instance (object) of the class will be initialized with the same values and it is not possible to initialize each instance of the class to different values.

When should we define the parameterized constructor in a class?

If we want to initialize object dynamically with the user given values then we should define the parameterized constructor.

Explain about parameterized constructor?

The developer given constructor with parameters is called as the parameterized constructor.

The advantage of a parameterized constructor is we can initialize each instance of the class with different values.

That means using parameterized constructor we can store a different set of values into different objects created to the class.

How many constructors can be defined in a class?

In a class, we can define multiple constructors but every constructor must have different parameters type and parameter order. So in a class, we can define one no-argument constructor plus ‘n’ number of parameterized constructors.

What is a copy constructor?

The constructor takes a parameter of class type is called as the copy constructor and this constructor is used to copy one object data into another object.

The main purpose of the copy constructor is to initialize a new object (instance) with the values of an existing object (instance).

That means this constructor is used to copy the data of an existing object into a newly created object that’s why this constructor is called as the copy constructor.

Explain about the static constructor?

We can create a constructor as static and when a constructor is created as static, it will be invoked only once. There is no matter how many numbers of instances (objects) of the class are created but it is going too invoked only once and that is during the creation of the first instance (object) of the class.

The static constructor is used to initialize static fields of the class and we can also write some code inside the static constructor that needs to be executed only once.

Static data fields are created only once in a class even though we are created any number of objects.

  1. There can be only one static constructor in a class.
  2. The static constructor should be without any parameter.
  3. It can only access the static members of the class.
  4. There should not be any access modifier in static constructor definition.
  5. If a class is static then we cannot create the object for the static class.
  6. Static constructor will be invoked only once i.e. at the time of first object creation of the class, from 2nd object creation onwards static constructor will not be called.
Can we initialize non-static data fields within the static constructor?

It is not possible to initialize non-static data fields within the static constructor, it raises a compilation error.

Can we initialize static data fields within the non-static constructor?

Yes, we can initialize static data fields within a non-static constructor but after then they lose their static nature.

Can we initialize static data fields in both static and non-static constructor?

Yes, we can initialize static data fields in both static and non-static constructors but static data fields lose their static nature.

Explain about private constructor?

We can also create a constructor as private.

The constructor whose accessibility is private is known as the private constructor.

When a class contains a private constructor then we cannot create an object for the class outside of the class.

Private constructors are used to creating an object for the class within the same class.

Generally, private constructors are used in Remoting concept.

When is a destructor method called?

A destructor method gets called when the object of the class is destroyed.

When will be the object of a class gets destroyed?

The object of a class will be destroyed by the garbage collector in any of the following cases

Case1: At the end of a program execution each and every object that is associated with the program will be destroyed by the garbage collector.

Case2: The Implicit calling of the garbage collector occurs sometime in the middle of the program execution provided the memory is full so that the garbage collector will identify unused objects of the program and destroys them.

Case3: The Explicit calling of the garbage collector can be done in the middle of a program execution with the help of “GC.Collect()” statement so that if there are any unused objects associated with the program will be destroyed in the middle of the program execution by the garbage collector.

What is a constructor in C#?

The constructor is a class method that is executed when an object of a class is created. A constructor has the same name as the class and usually used to initialize the data members of the new object. 

In C# what will happen if you do not explicitly provide a constructor for a class?

If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.

Structs are not referenced types. Can structs have constructors?

Yes, even though Structs are not referenced types, structs can have constructors.

We cannot create instances of static classes. Can we have constructors for static classes?

Yes, static classes can also have constructors.

Can you prevent a class from being instantiated?

Yes, a class can be prevented from being instantiated by using a private constructor.

Can a class or a struct have multiple constructors?

Yes, a class or a struct can have multiple constructors. Constructors in C# can be overloaded.

Can a child class call the constructor of a base class?

Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

namespace TestConsole
{
    class BaseClass
    {
        public BaseClass(string str)
        {
            Console.WriteLine(str);
        }
    }

    class ChildClass : BaseClass
    {
        public ChildClass(string str)
            : base(str)
        {
        }

        public static void Main()
        {
            ChildClass CC = new ChildClass("Calling base class constructor from child class");
        }
    }
}

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.

Can a class have a static constructor?

Yes, a class can have the static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.

namespace TestConsole
{
    class Program
    {
        static int I;
        static Program()
        {
            I = 100;
            Console.WriteLine("Static Constructor called");
        }
        public Program()
        {
            Console.WriteLine("Instance Constructor called");
        }
        public static void Main()
        {
            Program P = new Program();
        }
    }
}

Can you mark static constructor with access modifiers?

No, we cannot use access modifiers on the static constructor.

Can you have parameters for static constructors?

No, static constructors cannot have parameters.

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?

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.

Static constructors are also useful when creating wrapper classes for unmanaged code when the constructor can call the LoadLibrary method.

What is a Destructor?

A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.

Can a class have more than 1 destructor? 

No, a class can have only 1 destructor.

Can structs in C# have destructors?

No, structs can have constructors but not destructors, only classes can have destructors.

Can you pass parameters to destructors? 

No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.

Can you explicitly call a destructor?

No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.

Why is it not a good idea to use Empty destructors? 

When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

Is it possible to force the garbage collector to run?

Yes, it possible to force the garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance overhead. Usually, the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.

Usually, in .NET, the CLR takes care of memory management. Is there any need for a programmer to explicitly release memory and resources? If yes, why and how?

If the application is using an expensive external resource, it is recommended to explicitly releasing the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.

When do we generally use destructors to release resources?

If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.

When to use a Private constructor in c#?

There are several reasons for using private constructors

  1. When we want the caller of the class only to use the class but not instantiate. 
  2. If you want to ensure a class can have only one instance at given time, i.e. private constructors are used in implementing Singleton() design pattern.
  3. When a class has several overloads of the constructor, and some of them should only be used by the other constructors and not external code.

To learn more about constructor and destructor please read the below articles.

The Constructor in C#

The Destructor in C#

SUMMARY

In this article, I try to explain most frequently asked Constructor Interview Questions and Answers on C#.NET. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *