Constructor and Destructor In C#

By
We know that all objects that are created must be given initial values.we have used two approach to initialize the value of all the variables without constructors.
  1. The first approach uses the dot operator to access instance variables and then assigns values to them individually. It can be a tedious approach to initialize all the variables of all the objects.
  2. The second approach takes the help of a function like 'GetData' to initialize each object individually using statement like;    
        rect1.GetData(30,20);


Constructor:- Constructor is like a method which may contain some certain set of statement, But constructor does not have any Return Type and it will have the same name as the Class Name.
A Constructor is called automatically when object of class created.Basically constructor is used to Initialize the data member of class.We can use constructor overloading also in the program.
  • In case of parent child relationship ,when we make the object of child class, then child class constructor is called and base class default constructor is executed.
    EXAMPLE:-


using System;
namespace CONSTRUCTOR
{
    class Program
    {
        static void Main(string[] args)
        {
            employee emp = new employee("noida");//parameterised constructor of employee class is called which takes one aguments and default constructor of cls class is called.
            Console.WriteLine(emp.sname);  // default constructor of cls class is called which takes no aguments
            Console.WriteLine(emp.address);    //default constructor of employee class is called which takes no aguments
            Console.ReadLine();
        }
    }
    public class cls
    {
        public string sname;

        public cls()
        {
            sname = "abc";
            Console.WriteLine("Default constructor of cls");
        }
        public cls(string ram)
        {
            sname = ram;
            Console.WriteLine("paramerterise constructor of cls");
        }
    }
    public class employee : cls
    {
        public string address;
        public employee()
        {
            address = "mohannagar";
            Console.WriteLine("default constuctor of employee");
        }
        public employee(string shayam)
        {
            address = shayam;
            Console.WriteLine("paramerised constructor of employee");
        }
    }
}
   
  •  Open console application in your visual studio-> copy the above the code  and paste in Program.cs file->Run the application.
SEE  OUTPUT:-


  •  If we want to call a specific constructor of the base class through child class, the we can specify the "base" keyword with child class constructor.
  EXAMPLE:-

using System;
namespace BASE_KEYWORD_CONSTRUCTOR
{
    class Program
    {
        static void Main(string[] args)
        {
            employee emp = new employee("DELHI");
            Console.WriteLine(emp.sname);
            Console.WriteLine(emp.address);
           Console.ReadLine();
        }
    }
    public class cls
    {
        public string sname;

        public cls()
        {
            sname = "abc";
            Console.WriteLine("define constructor of cls");
        }
        public cls(string ram)
        {
            sname = ram;
            Console.WriteLine("paramerterise constructor of cls");
        }
    }
    public class employee : cls
    {
        public string address;
        public employee()
        {
            address = "mohannagar";
            Console.WriteLine("define constuctor of emp");
        }
        public employee(string shayam): base(shayam)
        {
            address = shayam;
            Console.WriteLine("paramerised constructor of employee");
        }
    }

}
OUTPUT :-  

    Constructor are usually Public ,because they are provided to create objects. we can use Private or Protected constructors also when we are using inheritance.

    Type of Constructors:- There are some type of constructor which are use in our program.
    1. Static Constructor:- Static member are those which is not changeable over whole program. Static Constructor is called automatically by CLR when class is loaded in first time in memory,before any object of class is created.
    2. Non Static Constructor:- Non static member are those member which is dynamically changes over the program. Non Static constructor(Instinct Constructor) is called whenever object of the class is created.
    EXAMPLE:-
    
    using System;
    using System.Data;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text;
    using System.Windows.Forms;
    namespace STATIC_AND_NONSTATIC_CONSTRUCTOR
    {
        class Program
        {
            static void Main(string[] args)
            {
                student obj1 = new student();
                student obj2 = new student("s");
                student.pname="pname is Rajesh";
                MessageBox.Show(student.pname);
            }
        }
    
        public class student
        {
            public static string pname;
            public string saddress;
            static student()
            {
                pname = "Microsoft";
                MessageBox.Show("STATIC CONSTRUCTOR IS CALLED");
              
            }
            public student()
            {
                MessageBox.Show("NON STATIC CONSTRUCTOR IS CALLED");
            }
            public student(string sadd)
            {
                string saddress = sadd;
                MessageBox.Show("NON STATIC PARAMETERISED CONSTRUCTOR IS CALLED");
            }
        }
        }
    
    
    OUTPUT :-




    Note:- Here i have shown  only one output,you can download whole application from the bottom and check complete output.


        3.   Private Constructor:In many situation, we may wish to define some utility classes that contain only static member such classes are never required to instantiate objects.Creating objects using such classes may be prevented by adding private constructor to the class.
       4.   Copy Constructor:- A copy constructor creates an object by copying variables from another object.  Since C# does not provided a copy constructor ,we must provide it ourselves if we wish to add this feature to the class.

    EXAMPLE:-

    
    Public value(value value)
    {
    code= value.code;
    price=value.price;
    }
    // creating objects in main class
    value value2= new value(value1);
    


    Note:- Here value2 is a copy of value1.
       
    Constructor Overloading:- Constructor overloading is like method overloading , In this  we have used same name but different signature of the Constructor. we have already discussed about signature in our previous  post. This is called constructor overloading. Constructor overloading is used when object are required  to perform similar task but using different input parameters. In Constructor overloading we use same name Constructor but there signature is different to perform similar functionality  in programs.
    EXAMPLE:-
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CONSTRUCTOR_OVERLOADING
    {
    
        namespace FlowerShop
    {
        public class Flower
        {
            public string Type;
            public string Color;
            public string Arrangement;
            public decimal UnitPrice;
    
            public Flower()
            {
                Type        = "";
                Color       = "Red";
                Arrangement = "Basket";
                UnitPrice   = 35.95M;
            }
     
            public Flower(string tp)
            {
                Type = tp;
                Color = "Red";
                Arrangement = "Basket";
                UnitPrice = 35.95M;
     }
        }
    
        class Program
        {
            static int Main()
            {
                Flower flr = new Flower("Tulips");
                Console.WriteLine("Flower Type:  {0}", flr.Type);
                Console.WriteLine("Flower Color: {0}", flr.Color);
                Console.WriteLine("Arrangement:  {0}", flr.Arrangement);
                Console.WriteLine("Price:        {0:C}", flr.UnitPrice);
                Console.WriteLine("");
                Console.ReadLine();
         return 0;
            }
        }
    }
    
    Note:- here we have used two constructor with same name but different signature, so it called constructor overloading.

    SEE OUTPUT:-

    This Keyword in C#:- When we refer to current member of the class then we can use "This" Keyword to refer that member.
    If we want to call a specific constructor of class through another constructor of the same class then we can specify "This" keyword with that constructor.
    EXAMPLE:-
    
    using System;
    
    namespace THIS_KEYWORD
    {
        class Program
        {
            static void Main(string[] args)
            {
                cls obj = new cls();
                Console.WriteLine(obj.sname);
                Console.ReadLine();
            }
        }
        public class cls
        {
            public string sname;
            public cls() : this("noida")
            {
                sname = "abc";
                Console.WriteLine("DEFINE OF CLS");
            }
            public cls(string sname)
            {
                this.sname = sname;
                Console.WriteLine("PARAM OF CLS");
            }
        }
    }
    

    Description:- Here I have used This keyword to call the same class constructor which takes one argument. you can download whole application from the bottom download link.
    OUTPUT:-

    Destructor:-   It is also like a method. It has not any return type and will have the same name as the class name but but prefix is used  '~'(tilde).
    It is called automatically when the object is no more than use,so to deallocate  the memory used by resources within the class.
    Destructor takes no arguments, so we can use only one destructor within the class and there will not use any access specifier with destructor.
    Example:-
    
    Class student
    {
    ------------------------------
    
    ------------------------------
    ~student() // No arguments
    {
    -------------------------------------
    -------------------------------------
    }
    } 
    Difference between Static and Non static Constructor:-
    There are some differences in Static and Non static Constructor which is given below:-
    • Static  Constructor  is called automatically by CLR when class is loaded in first time in memory and Instinct Constructor (non static constructor) is called whenever the object of the class is created.
    • We can pass parameter in in Non static Constructor but not to the Static Constructor.
    • There can be only one static Constructor and more than one Non static Constructor  within the class.
    • We can not use any Access specifier in static constructors but use within Non static Constructors  
    For More:-
    1.    File handling  Real Application
    2.  Host Asp.Net Application on IIS Server
    3. oops
    4. Different b/w HTML and XML
    5.  Make Captcha image for Asp.Net Application
    I hope this helpful for you.
    To Get the Latest  Free Updates Subscribe
    Click below for download whole application.
             Download

    0 comments:

    Post a Comment

    Powered by Blogger.