What are the different type of Constructor in C# ?


Constructor is the special method of class that will be executed whenever we will create the object of that class.

Some points

1. Class can have any number of constructors
2. Constructor doesn’t have any return type.
3. In one class we can create one static constructor

Type of Constructor in C#

1. Default constructor
2. Static Constructor
3. Private Constructor
4. Copy Constructor
5. Parameterized constructor

Default constructor

A constructor without any parameter is called the default constructor. This type of constructor dosnot take any parameter.

Sample Code

class Test
    {
        int a, b;
         public Test()
        {
            a = 10;
            b = 60;
        }
        static void Main(string[] args)
        {
            Test obj = new Test();
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.Read();
        }
    }

Parameterized Constructor:

A constructor with at least one parameter is called a Parameterized constructor. The advantage of a Parameterized constructor is that you can initialize each instance of the class to different values.


 class Test
    {
        int a, b;
         public Test(int x, int y)
        {
            a = x;
            b = y;
        }
        static void Main(string[] args)
        {
            Test obj = new Test(20,30);
            Test obj1 = new Test(200, 300);
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.WriteLine(obj1.a);
            Console.WriteLine(obj1.b);
            Console.Read();
        }
    }

Copy Constructor :

The constructor which creates an object by copying variables from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.

 class Test
    {
        private string Name;
        private string Address;
        public Test(Test objTest)
        {
            Name = objTest.Name;
            Address = objTest.Address;
        }

        public Test(string Name,string Address)
        {
            this.Name = Name;
            this.Address = Address;
        }
        public string Details
        {
            get
            {
                return "The address of " + Name + " Is " +Address.ToString();
            }
        }


        static void Main(string[] args)
        {
            Test obj = new Test("Chandradev","Bangalore");
            Test obj1 = new Test(obj);
            Console.WriteLine(obj1.Details);
            Console.Read();
        }
    }

Static Constructor:

A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

It will execute only once for all instances of class.

 class StaticTest
    {
        static StaticTest()
        {
            Console.WriteLine("This is the static constructor");
        }
        static void Main(string[] args)
        {
            StaticTest obj = new StaticTest();
            StaticTest obj1 = new StaticTest();
            Console.WriteLine("Hello World!");
            Console.Read();
        }
    }

Some points related with Static Constructors

1. A static constructor does not take access modifiers or have parameters.

2. A static constructor is called automatically to initialize the class before the first instance
is created or any static members are referenced.

3. A static constructor cannot be called directly.

4. The user has no control on when the static constructor is executed in the program.

5. 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.

Private Constructor

>> Private constructor is used to avoid the inheritance of class and we cant create the instance of that class.
>> private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

public class StaticTest
    {
        static void Main(string[] args)
        {
            Counter.currentCount = 10;
            Counter.IncrementCount();
            Console.WriteLine("New count: {0}", Counter.currentCount);
            Console.Read();
        }
    }
    public class Counter
    {
        private Counter() { }
        public static int currentCount;
        public static int IncrementCount()
        {
            return ++currentCount;
        }
    }

Some key points of a private constructor are:

1. One use of a private constructor is when we have only static members.

2. It provides an implementation of a singleton class pattern

3. Many time we don’t want to create instance of certain classes like utility, logs or conman routine classes in this scenario we can use the private constructor.

How to limit the number of object creation in c# ?


Hi All,

One time i got this question while giving the interview so i m going to write small note on this.

We can limit the number of object creation of class in C# using the static variable.

Static variable is used to share the value to all instance of that class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LINQ_Test
{
    public partial class Object_Creation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyClass obj = new MyClass();
            MyClass obj1 = new MyClass();
            MyClass obj2 = new MyClass();
            MyClass obj3 = new MyClass();
            MyClass obj4 = new MyClass();
            // MyClass obj5 = new MyClass(); 
            // Exception will throw
        }
    }

    public class MyClass
    {
        public static int Count = 0;
        public MyClass()
        {
            if (MyClass.Count==5)
            {
                throw new Exception("You canot create the object more than 5");
            }
            else
            {
                Count++;
            }
        }
    }
}

Note : In the above sample, we have created the static variable count, which will hold the incremented count value while creating the instance of that class.

What is the difference between Is and as Keyword in C# ?


Hi

One time i got this question in interview. Answer of this question , i have implemented in this code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//The is operator is used to check whether the run-time type of an object is compatible with a given

object num=10;
if (num is int)
{
Response.Write(“Num is integer”);
}

//The as operator is used to perform conversions between compatible types.

object ss = “This sis the string”;
string str = string.Empty;
if (ss is string)
{
str = ss as string;

Response.Write(str);
}

}
}