Skip to main content

Constructors

http://www.c-sharpcorner.com/UploadFile/puranindia/LearningConstructorsInC-sharp05182009044452AM/LearningConstructorsInC-sharp.aspx
Constructors
Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class, and usually initialize the data members of the new object.

What is constructor?

    *
      Constructor is used to initialize an object (instance) of a class.
    *
      Constructor is a like a method without any return type.
    *
      Constructor has same name as class name.
    *
      Constructor follows the access scope (Can be private, protected, public, Internal and external).
    *
      Constructor can be overloaded.


Constructors generally following types :

    *
      Default Constructor
    *
      Parameterized constructor
    *
      Private Constructor
    *
      Static Constructor
    *
      Copy Constructor


The constructor goes out of scope after initializing objects.

Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.

You need not to define default constructor it is implicitly defined.



Practical: Default Constructor

using System;
using
System.Collections.Generic;
using
System.Linq;
using System.Text;

namespace default_constructor
{
class Program
{
class c1
{
int
a, b;

public c1()
{
this.a =
10;
this.b = 20;
}

public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}",
b);
}
}

static void
Main(string[] args)
{
// Here when you create instance
of the class default constructor will be called.
c1
ob1 = new c1();
ob1.display();
Console.ReadLine();
}
}
}

Note: In the above practical example if you don't create a constructor still there will be a default constructor, which will initialize the data members of the class with some legal values.



Parameterized constructor

Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.
Practical: Parameterized Constructor

using System;
using
System.Collections.Generic;
using
System.Linq;
using System.Text;

namespace parameterized_constructor
{
class Program
{
class c1
{
int
a, b;

public c1(int x, int
y)
{
this.a = x;
this.b =
y;
}

public void
display()
{
Console.WriteLine("Value of a: {0}",
a);
Console.WriteLine("Value of b: {0}",
b);
}
}

static void
Main(string[] args)
{
// Here when you create instance
of the class parameterized constructor will be called.
c1
ob1 = new c1(10,
20);
ob1.display();
Console.ReadLine();
}
}

}


Private Constructor

Private constructors are used to restrict the instantiation of object using 'new' operator.  A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.


Practical: Private Constructor

 using System;
using
System.Collections.Generic;
using
System.Linq;
using System.Text;

namespace private_constructor
{
class Program
{

class c1
{
int a, b;

// Private constructor declared
here
private c1(int x, int
y)
{
this.a = x;
this.b =
y;
}

public static c1
create_instance()
{
return new c1(12,
20);
}

public void
display()
{
int z = a +
b;
Console.WriteLine(z);
}
}

static void
Main(string[] args)
{
// Here the class is initiated
using a static method of the class than only you can use private
constructor
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
}

Static Constructors

C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster.
Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.

Practical: Static Constructor

using System;
using
System.Collections.Generic;
using
System.Linq;
using System.Text;

namespace static_eg
{

class Program
{

public class test
{
static string name;
static int age;

static
test()
{
Console.WriteLine("Using static constructor to initialize static
data members");
name = "John Sena";
age
= 23;
}

public static void
display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}

}

static void
Main(string[] args)
{
test.display();
Console.ReadLine();
}
}


Copy Constructor

If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied. Practical: Copy Constructor

 using System;
using
System.Collections.Generic;
using
System.Linq;
using System.Text;

namespace copy_constructor
{

class Program
{

class c1
{
int a, b;

public
c1(int x, int y)
{
this.a = x;
this.b = y;
}

// Copy construtor
public c1(c1 a)
{
this.a =
a.a;
this.b = a.b;
}

public void display()
{
int z
= a + b;
Console.WriteLine(z);
}
}

static void
Main(string[] args)
{
c1
ob1 = new c1(10,
20);
ob1.display();
// Here we are using copy constructor. Copy constructor is using the
values already defined with ob1
c1 ob2 =
new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
}


Copy constructor sets behavior during runtime. It is shallow copying.
}


Comments

Popular posts from this blog

SQL Query :- Create Tables,Primary key,Foreign key,Merge Statment

SQL Query 1)    Using CASE Statement : - To Check the Particular column ISNULL              CASE WHEN ISNULL ([Col_Name], ' ') = ' ' THEN 'Others'                       ELSE [Col_Name] END AS [Col_Name] 2)    Convert Data format into VARCHAR and save 10/18/2012 this Format and also check if Date Column is Empty or not.                 CONVERT (VARCHAR,[Col_CreatedDt], 101) AS CreatedDt                        , CASE WHEN ISNULL ([Col_ModifiedDt], ' ') = ' ' THEN ' not available'                        ELSE CONVERT (VARCHAR, [ Col_ModifiedDt], 101) END AS ModifiedDt 3)    Casting  and Check Date Difference               CAST (Col_Name or ParameterName AS VARCHAR)               DATEDIFF(HOUR,Col_Date, GETDATE())<=24 4)    Create two table and set Primary key and Foreign Key             Create Table Exams            (                 exam_id int primary key,                 exam_name varchar(50),            );    

AngularJS

What is AngularJS? AngularJS is an open source web application framework. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3. Definition of AngularJS as put by its  official documentation  is as follows − AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you currently have to write. And it all happens within the browser, making it an ideal partner with any server technology. Features AngularJS is a powerful JavaScript based development framework to create RICH Internet Application(RIA). AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way. Application written in AngularJS is c

Check folder and Delete All Files from Existing Folder in C#

Dynamically check the Particular name Folder exist or not, it not exits create folder dynamically. if (!Directory.Exists(FolderName))         {             Directory.CreateDirectory(FolderName);         }         if (Directory.Exists(FolderName))         {             string[] filePaths = Directory.GetFiles(FolderName);             foreach (string filePath in filePaths)                 File.Delete(filePath);             //Directory.Delete(FolderName);                    }