Constructors in .NET Using C# with Singleton Pattern

Constructors in .NET Using C#. 

  • What is Constructor?

When a class or struct is created, its constructor is called. Constructors have the same name as the class or struct, and they usually initialize the data members of the new object.

  • How many type of constructors are in .NET?

Basically constructors are 5 types those are

      1.    Default Constructor

      2.    Parameterized Constructor

      3.    Copy Constructor

      4.    Static Constructor

      5.    Private Constructor

  • What is Default Constructor?

A default constructor is a constructor which can be called with no arguments.

Example:

using System;

 

namespace Constructors

{  

        class Customer

        {

            public int discount;

            public Customer()

            {

                discount = 10;

            }

        }

        class Program

        {

            static void Main(string[] args)

            {

                Customer obj = new Customer();

                // Once object of class created automatically constructor will be called

                Console.WriteLine("Default Discount for customer is : {0}", obj.discount);

                Console.ReadLine();

            }

        }   

}

Output:

 

 

  • What is Parameterized Constructors?

A parametrized constructor is a constructor which can be called with arguments.

  • Arguments can be of any type i.e int , float, string, array, list and of any object type.

  • Constructor can take any number of arguments.

Example is given below: 

using System;

 

namespace ParameterizedConstructors

{

    class Customer

    {

        public int discount;

        public Customer(int dis)

        {

            discount = dis;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Customer obj = new Customer(20);

            // Once object of class created automatically constructor will be called

            Console.WriteLine("Discount for customer is : {0}", obj.discount);

            Console.ReadLine();

        }

    }

}

Output : 

 

  • What is Copy Constructor?

A parameterized constructor that contains a parameter of same class type is called as copy constructor.  The Customer class defines a copy constructor that takes, as its argument, an instance of Customer. The values of the properties of the argument are assigned to the properties of the new instance of Customer. The code contains an alternative copy constructor that sends the CustomerName and ContactNumber properties of the instance that you want to copy to the instance constructor of the class.

Examples:

using System;

 

namespace CopyConstructors

{

    class Customer

    {

        public string CustomerName { get; set; }

        public string ContactNumber { get; set; }

        // Copy constructor.

        public Customer(Customer previousCustomer)

        {

            CustomerName = previousCustomer.CustomerName;

            ContactNumber = previousCustomer.ContactNumber;

        }

        // Instance constructor or parameterized constructor.

        public Customer(string CustName, string ContactNum)

        {

            CustomerName = CustName;

            ContactNumber = ContactNum;

        }

 

        public string Details()

        {

            return CustomerName + " Contact is :  " + ContactNumber;

        }

    }

 

    class TestCustomer

    {

        static void Main()

        {

            // Create a Customer object by using the instance constructor.

            Customer cust1 = new Customer("Joy", "88678-23456");

 

            // Create another Constructor object, copying cust1 object data.

            Customer cust2 = new Customer(cust1);

 

            // Change customer contact number. 

            cust1.ContactNumber = "98765-67854";

            cust2.ContactNumber = "87896-98765";

 

            // Change Customer's name.

            cust2.CustomerName = "Charles";

 

            // Show details to verify that the name and age fields are distinct.

            Console.WriteLine(cust1.Details());

            Console.WriteLine(cust2.Details());

 

            Console.ReadLine();

        }

    }

}

Output: 

 

  • What is Static Constructors?

It is possible to write a static no-parameter constructor for a class. Such

a constructor is executed only once, unlike the constructors, which are instance constructors that are executed whenever an object of that class is created.

 

It is possible to have a static constructor and a zero-parameter instance constructor defined in the same class. Although the parameter lists are identical, there is no conflict because the static constructor is executed when the class is loaded, but the instance constructor is executed whenever an instance is created.

Therefore, there is no confusion about which constructor is executed or when.

 

If you have more than one class that has a static constructor, the static constructor that will be executed first is undefined. Therefore, you should not put any code in a static constructor that depends on other static constructors having been or not having been executed. However, if any static fields have been given default values, these will be allocated before the static constructor is called.

 

The next example illustrates the use of a static constructor. To keep things simple, assume just one user preference, a quantity called BackColor that might represent the background color to be used in an application assume that the preference is to have a background color of red on weekdays and green on

weekends. All the program does is display the preference in a console window, but that is enough to see a static constructor at work:

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Drawing;

 

namespace StaticConstructors

{

    public class UserPreferences

    {

 

        public static readonly Color BackColor;

        static UserPreferences()

        {

            DateTime now = DateTime.Now;

            if (now.DayOfWeek == DayOfWeek.Saturday

            || now.DayOfWeek == DayOfWeek.Sunday)

                BackColor = Color.Green;

            else

                BackColor = Color.Red;

        }

        

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("User-preferences: BackColor  for "  + DateTime.Now.DayOfWeek + " is : "+ UserPreferences.BackColor.ToString());

            Console.ReadLine();

        }

    }

}

 

Output: 

 

  • What is private constructor?

•A Private Constructor is used to prevent the user to instantiate the class directly.

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

•If you don't use an access modifier with the constructor it will still be private by default.

•Private constructors are used to restrict the instantiation of object using 'new' operator.

•This type of constructors is mainly used for creating singleton object.

•We can use nested class (Inner Class) or static method to initialize a class having private constructor.

Example of singleton design pattern using private constructor.

              using System;

 

namespace PrivateConstructor

{

    public class Singleton

    {

        protected static Singleton _obj;

        //Private Constructor

        private Singleton()

        {

 

        }

        public static Singleton GetObject()

        {

            if (_obj == null)

            {

                _obj = new Singleton();

            }

            return _obj;

        }

        public void Print(string s)

        {

            Console.WriteLine(s);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Singleton SingletonObject = Singleton.GetObject();

            SingletonObject.Print("Hi, This is a Private constructor. Use of Singleton design pattern. Only one object for a class.");

            Console.ReadLine();

        }

    }

}

 

A very good example of Singleton Pattern using private constructor:

In below example there is two class Country and Currency which can be access through class SingletonPattern.  This instance of this class can be create only through the SingletonPattern and it is restricting to create more than one object. If the object is already created, then Singleton pattern will return the same instance and then you can change the currency information and country information means we can only one country object and currency object.

Example: 

using System;

 

namespace SingletonPattern

{

    public class Currency

    {

        public string CurrencySymbol { get; set; }

        public string CurrencyName { get; set; }

 

    }

    public class Country

    {

        public string CountryName { get; set; }

    }

 

    public sealed class SingletonPattern

    {

        // object which needs to be shared globally

        public Currency Currencies = new Currency();

        public Country Countries = new Country();

 

        // use static variable to create a single instance of the object

        static readonly SingletonPattern singleInstance = new SingletonPattern();

 

        /// This is a private constructor, meaning no outsides have access.

        private SingletonPattern()

        { 

        }

 

        public static SingletonPattern Instance

        {

            get

            {

 

                return singleInstance;

            }

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            SingletonPattern objSingle = SingletonPattern.Instance;

            Country objCuntry = objSingle.Countries;

            objCuntry.CountryName = "India";

            Currency objCurrency = objSingle.Currencies;

            objCurrency.CurrencyName = "Rupee";

            objCurrency.CurrencySymbol = "INR";

 

            Console.WriteLine("Example of perfect singleton pattern :");

            Console.WriteLine("Country Name : {0} ", objCuntry.CountryName);

            Console.WriteLine("Currency Name : {0}  and Currency Symbol : {1} " + Environment.NewLine, objCuntry.CountryName,objCurrency.CurrencySymbol);

 

            Console.ReadLine();

        }

    }

}

Output: 

  • How do we call Constructors from Other Constructors:

You might sometimes find yourself in the situation where you have several constructors in a class, perhaps to accommodate some optional parameters for which the constructors have some code in common. For example, consider the following:

using System;

 

namespace Constructors

{

    class Car

    {

        public string description;

        public uint nWheels;

        public Car(string description, uint nWheels)

        {

            this.description = description;

            this.nWheels = nWheels;

        }

        public Car(string description)

            : this(description, 4)

        {

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Car objCar1 = new Car("SUV",6);

            Console.WriteLine("Description : {0} and No. of wheels are : {1} ",objCar1.description,objCar1.nWheels);

            Car objCar2 = new Car("Micro");//Here no of wheel is default to 4 and it is calling constructor from other constructors.

            Console.WriteLine("Description : {0} and No. of wheels are : {1} ", objCar2.description, objCar2.nWheels);

            Console.ReadLine();

        }

    }

}

 

Output: 

 

9.What is Constructors for Struct :

You can define constructors for structs in exactly the same way that you can for classes, but you are not permitted to define a constructor that takes no parameters. This may seem nonsensical, but the reason is buried in the implementation of the .NET runtime. In some rare circumstances, the .NET runtime would not be able to call a custom zero-parameter constructor that you have supplied. Microsoft has therefore taken the easy way out and banned zero-parameter constructors for structs in C#. That said, the default constructor, which initializes all fields to zero values, is always present implicitly, even if you supply other constructors that take parameters. It’s also impossible to circumvent the default constructor by supplying initial values for fields. The following code will cause a compile-time error:

struct Dimensions

{

public double Length = 1; // error. Initial values not allowed

public double Width = 2; // error. Initial values not allowed

}

Of course, if Dimensions had been declared as a class, this code would have compiled without any problems.

Incidentally, you can supply a Close() or Dispose() method for a struct in the same way you do for a class.


Recommended Book for MVC : List of Some Important books for .NET Framework, C#, MVC, WCF


(Visited 412 times, 1 visits today)

Leave a Reply

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