Constructors & Destructors Review

Download Report

Transcript Constructors & Destructors Review

Constructors &
Destructors
Chapter-2
Continue
What is a 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.
Syntax of constructor:
[access-modifier] constructor_name (parameters)
{
// constructor body
}
The access-modifier is optional and can be private,
public, protected or internal. If no modifier is supplied,
then the default is private.
The constructor_name of a constructor must be the
same as the name of the class.
The constructor body can be used to initializes the
object into a known starting state.
Execution Of constructor
public class MySimpleClass
{
public MySimpleClass (int x)
{
Console.WriteLine (x);
}}
When the object of this class is instantiated this
constructor will be executed. Something like this :
mySampleClass obj = new mySampleClass()
// At this time the code in the constructor will // be
executed
Comments on constructors

A constructor is called automatically whenever a new
instance of a class is created.

You must supply the arguments to the constructor when
a new instance is created.

If you do not specify a constructor, the compiler
generates a default constructor for you (expects no
parameters and has an empty body).
Constructors types :





Default Constructor
Parameterized constructor
Private Constructor
Static Constructor
Copy Constructor
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.
Example of Default Constructor
using System;
using System.Collections.Generic;
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 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.
public mySampleClass(int Age, string Name)
{
// This is the constructor with two parameters.
// Parameterized Constructor
}
// rest of the class members goes here.
}
using System;
using System.Collections.Generic;
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.
If you don't want the class to be inherited we declare its
constructor private.
Private Constructor


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.
Example of Private Constructor
using System;
using System.Collections.Generic;
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.
Static Constructors

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.

using System;
using System.Collections.Generic;
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.
If you create a new object and want to copy the values
from an existing object, you use copy constructor.
using System;
using System.Collections.Generic;
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;
}
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();
}
}
}
Destructors






Destructors are used to destruct instances of classes.
Destructors cannot be defined in structs. They are
only used with classes.
A class can only have one destructor.
Destructors cannot be inherited or overloaded.
Destructors cannot be called. They are invoked
automatically.
A destructor does not take modifiers or have
parameters.
Destructors
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
class First
{
~First()
{
System.WriteLine("First's destructor is called.");
}}
class Second : First
{
~Second()
{
System.WriteLine("Second's destructor is called.");
}}
class Third : Second
{
~Third()
{
System.Diagnostics.Trace.WriteLine("Third's destr
uct
or is called.");
}
}
class TestDestructors
{ static void Main()
{
Third t = new Third();
}}
Understanding Properties and
Indexers



A property is like a "virtual field" that contains get and
set accessor and provides an interface to the
members of a class.
They can be used to get and set values to and from
the class members.
Properties can be static or instance members of a
class.
Understanding Properties and
Indexers


The get accessor does not accept any parameter;
rather it returns the value of the member that it is
associated with.
The set accessor contains an implicit parameter
called 'value'. The following code example illustrates
a simple property.
C# Properties



Provide procedural access to data
 Like accessors
But have syntax similar to direct variable access
 foo.X instead of foo.getX();
Minor feature, but provides substantial improvement
in readability and fluidity of programming
C#
Property
Syntax
[access-modifiers] return-type property-name
{
}




get
{
… sequence of statements ending in a return
}
set
{
… sequence of statements
}
get accessor
set accessor
Get accessor returns value of same type as “return type”
Set accessors have implicit parameter named “value”
 Use to set internal data representation
Properties can be public, private, protected
 Public: any class can access, private: only that class,
protected: that class and children
By convention, property names have initial capital
C# Property Example
public class GameInfo
{
private string name;
// Test code
GameInfo g = new
GameInfo();
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
// Call set accessor
g.Name = “Radiant
Silvergun”;
}
// Call get accessor
System.Console.Write(g.
Name);
C# Automatic Property Example
public class GameInfo
{
public string Name
{get; set;}
}
// Test code
GameInfo g = new
GameInfo();
// Call set accessor
g.Name = “Radiant
Silvergun”;
// Call get accessor
System.Console.Write(g.
Name);
This property behaves the same as the first property
example, two slides ago.
A private class variable, private String name, is
automatically created.
using System;
class Test
{
private int number;
public int MyProperty
{ get
{
return number;
}
set
{
number = value;
}}
Public static void Main(string[ ]args)
{
Test t1 = new Test();
t1.MyProperty = 100;
Console.WriteLine(t1.MyProperty);
Console.ReadLine();
}
}
}
Implementing a static property

The static property MyProperty can be accessed without
instantiating the class. A static property can access static
members of a class only.
using System;
class Test
{
private static int number;
public static int MyProperty
{ get
{
return number;
}
set
{
number = value;
}}
Public static void Main(string[]args)
{
Test.MyProperty = 100;
Console.WriteLine(Test.MyProperty);
Console.ReadLine();
}
}
}
Restricting the visibility of
Property

The following code shows how the visibility of the get
and the set accessors has been restricted to the current
assembly only by using the keyword "internal".
public class Employee
{
private int empID;
private string empName;
internal int ID
{ get
{
return empID;
}
set
{
empID = value;}}
internal string Name
{
get
{
return empName;
}
set
{
empName = value;
}
}
}
public class Test
{
public static void Main(string[ ]args)
{
Employee emp = new Employee();
emp.Name = "Joydip";
emp.ID = 259;
System.Console.WriteLine ("The id is:" + emp.ID);
System.Console.WriteLine ("The name is:" + emp.Name);
}
}
 The keyword “internal” implies that the property's ID and
Name can be accessed from the current assembly only
as they are “internal” to the assembly in which they have
been declared.
Indexer




Indexers are also called smart arrays in C# and can
be used to treat an object as an array. An indexer
allows an instance of a class or a struct to be indexed
as an array, which is useful for looping or iterating or
data binding operations.
All indexers should accept at least one parameter.
Indexers cannot be static. This is because static
methods do not have access to ‘this’.
The ‘this’ keyword indicates an instance of the current
class. Look at the code given below.
Indexer
The following is the syntax of an indexer declaration.
<Modifier> <Return type> this[arguments]
{
get
{
}
Set
{
}
}
using System;
class Employee
{
private string[ ]name = new string[10];
public string this[int index]
{
get
{
return name[index];
}
set
{
name[index] = value; }}}
class Test
{
public static void Main()
{
Employee emp = new Employee();
emp[0] = "Joydip";
emp[1] = "Manashi";
emp[2] = "Jini";
Console.WriteLine("The names are:--");
for (int i = 0; i < 3;Console.WriteLine(emp[i++]))
;
Console.ReadLine();
}}}
The output of the program is




The names are:-Joydip
Manashi
Jini
Indexers in inheritance
using System;
class Base
{
public int number;
public int this[int index]
{
get
{
Console.Write("Get of the baseclass.");
return number;
}
set
{
Console.Write("Set of the base class.");
number = value;
} }}
class Derived: Base{}
class Test
{
public static void Main()
{
Derived d = new Derived();
d[0] = 500;
Console.WriteLine ("The value is: "+ d[0]);
}}
Comparison between properties
and indexers
Property:
Indexer: -
-Identified by its name.
Identified by its signature.
-Accessed through a simple name or a
member access.
-Accessed through an element access.
-Must be an instance member.
-Can be a static or an instance member.
-A get accessor of a property has no
parameters.
-A set accessor of a property contains the
implicit value parameter.
-A get accessor of an indexer has the
same formal parameter list as the indexer.
-A set accessor of an indexer has the
same formal parameter list as the indexer,
in addition to the value parameter.