C# Interview Questions on constructors


What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. 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 reference types. Can structs have constructors?
Yes, even though Structs are not reference 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 as shown in the example below.

using System;
namespace TestConsole
{
  class Program
  {
    public static void Main()
    {
      //Error cannot create instance of a class with private constructor
      SampleClass SC = new SampleClass();
    }
  }
  class SampleClass
  {
    double PI = 3.141;
    private SampleClass()
    {
    }
  }
}


Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp 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.

using System;
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.

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();
    }
  }
}

Will the following code compile?
using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    //Call the base class contructor from child class
    public ChildClass() : base("A call to base class constructor")
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

Can a class have static constructor?
Yes, a class can have 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.

using System;
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 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?
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.

19 comments:

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

    its not true

    ReplyDelete
  2. C# provide copy constructor.

    ReplyDelete
    Replies
    1. c#provide copy constructor but it is a special parametrize constructor

      Delete
  3. C# does not provide a COPY construtor.
    Please refer:
    http://msdn.microsoft.com/en-us/library/ms173116(VS.80).aspx

    ReplyDelete
  4. Can you give a practical application where you would need to define a constructor as private? May be for implementation of Singleton class..is what I could think of!

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


    This code will compile, we need not call base class consstructor in child class constructor

    ReplyDelete
    Replies
    1. Did u tested before u comment ? plz check and comment do not mislead others

      Delete
    2. if u make obj of child class then firstly your child class constructor called but this child class constr.in turn call its base class constructor(by default default constructor)
      because in child class obj base class obj is initialize first and then child clas obj will created this is the reason why base class obj does not have child members because obj give you all what it contain not from outside

      Delete
    3. thanks venkat sir to share your great knowledge with us.

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

    Compiler won't allow to compil this code...it will show constructor error.

    ReplyDelete
  7. The Above code will only run if you use base keyword

    ReplyDelete
  8. yes he is right. please always consult MSDN for problems.

    Syyed
    MVP
    Principle Software Engineer
    Microsoft Newyork

    ReplyDelete
  9. can we override constructor

    ReplyDelete
  10. C# Provides Copy Constructor...

    class Person
    {
    private string name;
    private int age;

    // Copy constructor.
    public Person(Person previousPerson)
    {
    name = previousPerson.name;
    age = previousPerson.age;
    }



    // Instance constructor.
    public Person(string name, int age)
    {
    this.name = name;
    this.age = age;
    }

    // Get accessor.
    public string Details
    {
    get
    {
    return name + " is " + age.ToString();
    }
    }
    }

    class TestPerson
    {
    static void Main()
    {
    // Create a new person object.
    Person person1 = new Person("George", 40);

    // Create another new object, copying person1.
    Person person2 = new Person(person1);
    Console.WriteLine(person2.Details);

    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
    }
    }
    // Output: George is 40

    ReplyDelete
    Replies
    1. C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.

      Delete
  11. Constructors are 2 types
    - - - - - - - - - - - - - - - - - - -
    1.Instance Constructors
    2.Non-Instance Constructors

    Instance Constructors are 4 types
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    1.Default Constructor(Default Constructor 2 Types : 1.User Defined Default Constructor, 2.System Defined Default Constructor)
    2.Parameterized Constructor
    3.Copy Constructor
    4.Private Constructor

    Non-Instance Constructor is one type
    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    1.Static Constructor

    ReplyDelete
  12. A static class can have static constructor, and the use of this constructor is initialization of static member. And static constructor get called only once when you have access any type member of static class with class name

    ReplyDelete
  13. what is default access specifier for class,constructor in C#.?,pls some one help me out

    ReplyDelete
  14. We cannot create instances of static classes. Can we have constructors for static classes?
    Yes, static classes can also have constructors.
    NOTE: STATIC CONSTRUCTOR ONLY

    ReplyDelete

If you are aware of any other C# questions asked in an interview, please post them below. If you find anything missing or wrong, please feel free to correct by submitting the form below.

 
Disclaimer - Terms of use - Contact Us