Saturday, October 24, 2020

Classes In C#

Class is consists of data and behavior. Class data is represented by it's fields and behavior is represented by its methods. 

Example:

class Customer
    {
        string first_Name;
        string last_Name;

        //Default parameterless constructor
        public Customer() : this("No FirstName Provided", "No LastName Provided")
        {

        }
        public Customer(string f_Name,string l_Name)
        {
            this.first_Name = f_Name;
            this.last_Name = l_Name;
        }

        public void printFullName()
        {
            Console.WriteLine("Full Name = {0}" ,this.first_Name+" "+this.last_Name);
        }

        ~Customer()//destructor call automatically
        {
            //Clean up code
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer C1 = new Customer("Brij","Pal"); //here constructor used to initializing the member of class
            C1.printFullName();

            Customer C2 = new Customer(); //Here called the default constructor
            C2.printFullName();

            Console.ReadLine();
        }
       
    }

Purpose of Constructors:
  • The purpose of a class constructor is to initialize class fields. A class constructor is automatically called when an instance of class is created.
  • Constructor do not have a return values and always have the same name as the class name.
  • Constructors are not mandatory. if we do not provide a constructor, a default parameter less constructor is automatically provided.
  • Constructors can be overloaded by the number and type of parameters. 
Destructors:
  1. Destructors have the same name as the class with ~symbol in front of them.
  2. They don't take any parameters and do not return a value.
  3. Destructors are places where you could put code to release any resources your class was holding during lifetime.
  4. They are normally called when the C# garbage collector decides to clean your object from memory. 

No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...