Class Constructors Interview questions


This is my first post about the C# Interview questions. I will try to cover here core concept of C# language (.Net2.0) and try to touch each and every areas which is asking in interviews.

What is the Constructors?

– Constructors are Class method that are executed when class is instantiated with new keyword
– Constructors have same name as Class name
– Usually initialize data member of class

What is the defalut Constructor?

– If Constructors take no parameter called default constructor

How to call base class constructor? OR What is the use of “base” key word in terms of Constructor?
– A constructor can use the base keyword to call the constructor of a base class

public class MyBaseClass
{
    public MyBaseClass (int x) : base() // Invoke the parameterless constructor in object
    {
        Console.WriteLine ("In the base class constructor taking an int, which is "+x);
    }
}

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass () : this (5) // Invoke the MyDerivedClass constructor taking an int
    {
        Console.WriteLine ("In the derived class parameterless constructor.");
    }

    public MyDerivedClass (int y) : base (y+1) // Invoke the MyBaseClass constructor taking an int
    {
        Console.WriteLine ("In the derived class constructor taking an int parameter.");
    }

    public MyDerivedClass (string x) : base (10) // Invoke the MyBaseClass constructor taking an int
    {
        Console.WriteLine ("In the derived class constructor taking a string parameter.");
    }
}

How to invoke another constructor in same object?

– A constructor can invoke another constructor in the same object using the this keyword

public class MyClass
{
        string data1;
        string data2;
        public MyClass(string paraData1)
        {
              data1=paraData1;
        }
        public MyClass(string paraData1, string paraData2):this(paraData1)
        {
                data2 = paraData2;
        }
}

Instance Constructors

If a class does not have any Constructor then what would be happened?

– If any class does not have any constructor then a default constructor is automatically provided and fields are initialize with their default values

public class Person
{
       public int age;
       public string name;
}
 
class TestPerson
{
    static void Main()
    {
        Person p = new Person();
 
        System.Console.Write(“Name: {0}, Age: {1}”, p.name, p.age);
    }
}
 

Output:

Name: , Age: 0

Notice that the default value of age is 0 and the default value of name is null

What is the Private Constructors and what is the use of it?

– A private constructor is a special instance constructor. It is commonly used in classes that contain static members only
– If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class

public class Counter
{
    private Counter() { }
    public static int currentCount;

    public static int IncrementCount()
    {
        return ++currentCount;
    }
}

class TestCounter
{

    static void Main()
    {

        // If you uncomment the following statement, it will generate
        // an error because the constructor is inaccessible:
        // Counter aCounter = new Counter();   // Error
 

        Counter.currentCount = 100;
        Counter.IncrementCount();
        System.Console.WriteLine(“New count: {0}”, Counter.currentCount);
    }
}

What is the  Static Constructors and what is the use of it?

– A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only
– It is called automatically before the first instance is created or any static members are referenced
– A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced
– A static constructor cannot be called directly
– The user has no control on when the static constructor is executed in the program
– 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

class Test
{
     //Declaration and initialization of static data member
     private static int id = 5;
     public static int Id
     {
         get{return id;}
       }
       public static void print()
       {
            Console.WriteLine("Test.id = " + id);
       }
}
      static void Main(string[] args)
     {
             //Print the value of id
             Test.print();
     }

What is the Copy  Constructors?

If you create a new object and want to copy the values from an existing object

        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);
                System.Console.WriteLine(person2.Details);
            }
        }

If you want any clarification the please let me know.

Thanks,

Parwej Ahama

e: ahamad.parwej@gmail.com

Advertisements
Tagged with: , , , ,
Posted in .Net, C#
One comment on “Class Constructors Interview questions
  1. Suresh says:

    write about Constructor chaining

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Top Rated

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Blog Stats
  • 29,596 hits
%d bloggers like this: