Anda di halaman 1dari 15

C# BASICS

By,manish pushkar Quaarc Solutions

Constructor and Destructor In C#


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."et#ata$%&'2&(!

Constructor:- )onstructor is like a method which may contain some certain set of statement' *ut constructor does not have any Return Type and it will have the same name as the )lass Name. + )onstructor is called automatically when object of class created.*asically 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 e,ecuted. -.+/01-23

4
1 using System; 2 namespace CONSTRUCTOR 3 { 4 5 6 7
class Program { static void Main(string[] args) { employee emp = new employee("noida");//parameterised

8 constructor of employee class is called which takes one aguments and 9


default constructor of cls class is called. Console.WriteLine(emp.sname); // default constructor of cls

10class is called which takes no aguments

C# BASICS
By,manish pushkar Quaarc Solutions
Console.WriteLine(emp.address); //default constructor of employee class is called which takes no aguments Console.ReadLine();

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

} } public class cls { public string sname;

public cls() { sname = "abc"; Console.WriteLine("Default constructor of cls"); } public cls(string ram) { sname = ram;

26
Console.WriteLine("paramerterise constructor of cls");

27
}

28 29 30 31 32 33 34 35

} public class employee : cls { public string address; public employee() { address = "mohannagar"; Console.WriteLine("default constuctor of employee");

C# BASICS
By,manish pushkar Quaarc Solutions
} public employee(string shayam) { address = shayam; Console.WriteLine("paramerised constructor of employee");

36 37 38 39 40

41
}

42
}

43

5pen console application in your visual studio36 copy the above the code and paste in 0rogram.cs file367un the application. 8-- OUT UT23

If we want to call a specific constructor of the base class through child class' the we can specify the 9base! keyword with child class constructor.

C# BASICS
By,manish pushkar Quaarc Solutions

-.+/01-23 4
1 using System; 2 namespace BASE_KEYWORD_CONSTRUCTOR 3 { 4 5 6 7 8 9 10 11
} class Program { static void Main(string[] args) { employee emp = new employee("DELHI"); Console.WriteLine(emp.sname); Console.WriteLine(emp.address); Console.ReadLine();

12
}

13
public class cls

14
{

15
public string sname;

16 17
public cls()

18
{

19 20 21 22 23 24
}

sname = "abc"; Console.WriteLine("define constructor of cls");

public cls(string ram) { sname = ram;

C# BASICS
By,manish pushkar Quaarc Solutions
Console.WriteLine("paramerterise constructor of cls"); } } public class employee : cls {

25 26 27 28 29

public string address;

30
public employee()

31
{

32
address = "mohannagar";

33
Console.WriteLine("define constuctor of emp");

34 35 36 37 38 39 40 41 42 43 44
} }

} public employee(string shayam): base(shayam) { address = shayam; Console.WriteLine("paramerised constructor of employee"); }

C# BASICS
By,manish pushkar Quaarc Solutions

OUT UT :-

)onstructor are usually ublic 'because they are provided to create objects. we can use 0rivate or 0rotected constructors also when we are using inheritance.

Type o" Constructors:- There are some type of constructor which are
use in our program. 1. #tatic Constructor:- 8tatic member are those which is not changeable over whole program. 8tatic )onstructor is called automatically by C$R when class is loaded in first time in memory'before any object of class is created. 2. Non #tatic Constructor:- :on static member are those member which is dynamically changes over the program. :on 8tatic constructor$Instinct )onstructor( is called whenever object of the class is created.

C# BASICS
By,manish pushkar Quaarc Solutions

%&'( $%:4
1
using System;

2
using System.Data;

3
using System.Collections.Generic;

4
using System.Linq;

5
using System.Text;

6
using System.Text;

7
using System.Windows.Forms;

8
namespace STATIC_AND_NONSTATIC_CONSTRUCTOR

9
{

10
class Program

11 12 13 14 15 16 17 18 19 20 21 22 23

{ 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;

24

C# BASICS
By,manish pushkar Quaarc Solutions

25 26 27 28 29

static student() { pname = "Microsoft"; MessageBox.Show("STATIC CONSTRUCTOR IS CALLED");

30
public student()

31
{

32
MessageBox.Show("NON STATIC CONSTRUCTOR IS CALLED");

33
}

34
public student(string sadd)

35 36 37 38 39
}

{ string saddress = sadd; MessageBox.Show("NON STATIC PARAMETERISED CONSTRUCTOR IS

CALLED"); }

40
}

41

OUT UT :-

C# BASICS
By,manish pushkar Quaarc Solutions

:ote23 ;ere i have shown only one output'you can download whole application from the bottom and check complete output.

). ri*ate Constructor:- In many situation' we may wish to define some utility classes that contain only static member such classes are never re<uired to instantiate objects.)reating objects using such classes may be prevented by adding private constructor to the class. +. Copy Constructor:- + copy constructor creates an object by copying variables from another object. 8ince )= does not provided a copy constructor 'we must provide it ourselves if we wish to add this feature to the class. %&'( $%:4 1Public value(value value)
2{ 3code= value.code; 4price=value.price; 5} 6 7
// creating objects in main class value value2= new value(value1);

Note:- ;ere value2 is a copy of value1.

C# BASICS
By,manish pushkar Quaarc Solutions

Constructor O*erloadin,:- )onstructor overloading is like method


overloading ' In this we have used same name but different si,nature of the )onstructor. we have already discussed about si,nature in our previous post. This is called constructor overloading. )onstructor overloading is used when object are re<uired to perform similar task but using different input parameters. In )onstructor overloading we use same name )onstructor but there signature is different to perform similar functionality in programs. -.+/01-23 4
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace CONSTRUCTOR_OVERLOADING 7 { 8 9 10{ 11 12 13 14 15 16 17 18 19
public Flower() { public class Flower { public string Type; public string Color; public string Arrangement; public decimal UnitPrice; namespace FlowerShop

10

C# BASICS
By,manish pushkar Quaarc Solutions
Type Color = ""; = "Red";

20 21 22 23
}

Arrangement = "Basket"; UnitPrice = 35.95M;

24 25
public Flower(string tp)

26
{

27
Type = tp;

28 29 30 31 } 32 33 34 35 36 37 38 39
}

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);

40
Console.WriteLine("Arrangement: {0}", flr.Arrangement); {0:C}", flr.UnitPrice);

41
Console.WriteLine("Price:

42 43 44

Console.WriteLine(""); Console.ReadLine(); return 0;

11

C# BASICS
By,manish pushkar Quaarc Solutions
} }

45 46 47 48 49
}

Note:- here we have used two constructor with same name but different signature' so it called constructor overloading. #%% OUT UT:-

12

C# BASICS
By,manish pushkar Quaarc Solutions

This -ey.ord in C/:- When we refer to current member of the class


then we can use 9This! >eyword 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 9This! keyword with that constructor. -.+/01-23 4
using System;

1 2
namespace THIS_KEYWORD

3
{

4
class Program

5
{

6
static void Main(string[] args)

7
{

8 9 10 11 12 13 14 15 16 17 18 19
} } }

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");

20
public cls(string sname)

13

C# BASICS
By,manish pushkar Quaarc Solutions
{ this.sname = sname; Console.WriteLine("PARAM OF CLS"); }

21 22 23 24
}

25
}

26 27 28

Description:- ;ere 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. 5?T0?T23

14

C# BASICS
By,manish pushkar Quaarc Solutions

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 prefi, is used

010$tilde(.

It is called automatically when the object is no more than use'so to deallocate the memory used by resources within the class. #estructor takes no arguments' so we can use only one destructor within the class and there will not use any access specifier with destructor. Example:4
1
Class student

2
{

3 -----------------------------4 5 -----------------------------6 ~student() // No arguments 7 { 8 ------------------------------------9


------------------------------------}

10
}

11

Di""erence bet.een #tatic and Non static Constructor:There are some differences in 8tatic and :on static )onstructor which is given below23

8tatic )onstructor is called automatically by )17 when class is loaded in first time in memory and Instinct )onstructor $non static constructor( is called whenever the object of the class is created. We can pass parameter in in :on static )onstructor but not to the 8tatic )onstructor. There can be only one static )onstructor and more than one :on static )onstructor within the class. We can not use any 'ccess speci"ier in static constructors but use within :on static )onstructors

15

Anda mungkin juga menyukai