SlideShare a Scribd company logo
1 of 37
Class
• A class is a construct that enables you to create your
own custom types by grouping together variables of
other types, methods and events. A class is like a
blueprint. It defines the data and behavior of a type. If
the class is not declared as static, client code can use it
by creating objects or instances which are assigned to a
variable. The variable remains in memory until all
references to it go out of scope.
Objects
• Objects are programming constructs that have
data, behavior, and identity. Object data is
contained in the fields, properties, and events of
the object, and object behaviors are defined by
the methods and interfaces of the object.
• Objects have identity — two objects with the
same set of data are not necessarily the same
object.
• Objects in C# are defined through classes and
structs — these form the single blueprint from
which all objects of that type operate.
Constructor
• A constructor initializes an object when it is created. It
has the same name as its class and is syntactically
similar to a method. However, constructors have no
explicit return type. The general form of a constructor
is shown here:
access class-name(param-list)
{
// constructor code
}
• This constructor is called by new keyword when an
object is created. For example, in the line
• MyClass t1 = new MyClass();
Parameterized Constructors/
Overloaded constructor
• class MyClass {
• public int x;
• public MyClass(int i) {
•
x = i;
• }
• }
Static Constructors
• A constructor can also be specified as static. A static
constructor is typically used to initialize features that
apply to a class rather than an instance. Thus, it is
used to initialize aspects of a class before any objects of
the class are created. Here is a simple example:
using System;
class Cons {
public static int alpha;
public int beta;
// A static constructor.
static Cons() {
alpha = 99;
Console.WriteLine("Inside static constructor.");
}
•
•
•
•
•
•
•
•
•
•
•
•
•

// An instance constructor.
public Cons() {
beta = 100;
Console.WriteLine("Inside instance constructor.");
}
}
class ConsDemo {
static void Main() {
Cons ob = new Cons();
Console.WriteLine("Cons.alpha: " + Cons.alpha);
Console.WriteLine("ob.beta: " + ob.beta);
}
}

• Here is the output:
•
•
•
•

Inside static constructor.
Inside instance constructor.
Cons.alpha: 99
ob.beta: 100
Static Classes
• A class can be declared static. There are two key
features of a static class.
• First, no object of a static class can be created.
• Second, a static class must contain only static
members. A static class is created by modifying a class
declaration with the keyword static, shown here:
• static class Program
•
{
•
static void Main(string[] args)
•
{
•
Console.WriteLine("this is static class constructor");
•
}
•
}
Constructor Chaining
• When working with overloaded constructors, it is
sometimes useful for one constructor to invoke
another.
• In C#, this is accomplished by using another form
of the this keyword.
• When the constructor is executed, the overloaded
constructor that matches the parameter list
specified by parameter-list2is first executed.
• Then, if there are any statements inside the original
constructor, they are executed.
•
•
•
•
•
•
•
•
•
•
•

class Car
{
private string description;
private uint nWheels;
public Car(string model, uint nWheels)
{
this.description = description;
this.nWheels = nWheels;
}
public Car(string model) : this(model, 4)
{}

• Car myCar = new Car(“Proton Persona”);
Private Constructors
• In C# there are no global methods or constants.
You might find yourself creating small utility
classes that exist only to hold static members.
Setting aside whether this is a good design or
not, if you create such a class you will not want
any instances created.
• You can prevent any instances from being
created by creating a default constructor
(one with no parameters) which does
nothing, and which is marked private. With no
public constructors, it will not be possible to
create an instance of your class.
readonly
• You can create a read-only field in a class by
declaring it as readonly.
• A readonly field can be given a value only by
using an initializer when it is declared or by
assigning it a value within a constructor.
• Once the value has been set, it can’t be
changed outside the constructor.
• Thus, a readonly field is a good way to create a
fixed value that has its value set by a
constructor.
•
•
•
•
•
•
•
•
•
•
•
•
•

using System;
class MyClass {
public static readonly int SIZE = 10;
}
class DemoReadOnly {
static void Main() {
int[] source = new int[MyClass.SIZE];
for(int i=0; i < MyClass.SIZE; i++)
source[i] = i;
// Give source some values.
foreach(int i in source)
Console.Write(i + " ");
Console.WriteLine();
Passing by Reference
• C# provides the ref parameter modifier for
passing value into a method by reference
and the out modifier for those cases in
which you want to pass in a ref variable
without first initializing it.
• The ref parameter modifier causes C# to
create a call-by-reference, rather than a
call-by-value. The ref modifier is
specified when the method is declared
and when it is called.
Use ref
class RefTest {
// This method changes its argument. Notice the use of ref.

public void Sqr(ref int i) {
i = i * i; }}
class RefDemo {
static void Main() {
RefTest ob = new RefTest();
int a = 10;
Console.WriteLine("a before call: " + a);
ob.Sqr(ref a);
// notice the use of ref
Console.WriteLine("a after call: " + a);
}
}

output
a before call: 10
a after call: 100
Out
• The out modifier removes the requirement that
a reference parameter be initiailzed.
• The parameters to GetTime( ), for example,
provide no information to the method; they are
simply a mechanism for getting information
out of it.
• Thus, by marking all three as out parameters,
you eliminate the need to initialize them outside
the method.
• Within the called method the out parameters
must be assigned a value before the method
returns. Here are the altered parameter
declarations for GetTime( ):
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

class Decompose {
public int GetParts(double n, out double frac) {
int whole;
whole = (int) n;
frac = n - whole; // pass fractional part back through frac
return whole;
// return integer portion
}}
class UseOut {
static void Main() {
Decompose ob = new Decompose();
int i;
double f;
i = ob.GetParts(10.125, out f);
Console.WriteLine("Integer portion is " + i);
Console.WriteLine("Fractional part is " + f);
}}
Reference Parameter
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
t.GetTime( ref theHour, ref theMinute, ref theSecond);
Out Parameter
public void GetTime(out int h, out int m, out int s)
{
h = Hour;
m = Minute;
s = Second;
}
Ref/ Out
• Value types are passed into methods by
value. Ref parameters are used to pass
value types into a method by reference.
This allows you to retrieve their
modified
value
in
the
calling
Programming C# method.
• Out parameters are used only to return
information from a method.
Calling Base Class Constructors
• A derived class can call a constructor
defined in its base class by using an
expanded form of the derived class’
constructor declaration and the base
keyword.
derived-constructor (parameter-list ) :
base( arg-list ) {
// body of constructor
}
• arg-list specifies any arguments needed
by the constructor in the base class.
• Notice the placement of the colon.
class Program
{
public int i=0, j=0;
public Program(int a, int b)
{
i = a;
j = b;
}
public void show1()
{
Console.WriteLine(“Base class"+i+j);
} }
class D:Program
{
string s1;
public D(string s, int a, int b): base(a, b)
{
s1 = s;
}
public void sh()
{ Console.WriteLine(s1+i+j); }
static void Main(string[] args)
{
D d1 = new D(“Drive Class ", 5, 8);
d1.sh();} }
Name Hiding
• It is possible for a derived class to define a
member that has the same name as a
member in its base class.
• When this happens, the member in the base
class is hidden within the derived class.
• If your intent (goal or aim) is to hide a base
class member, then to prevent warning, the
derived class member must be preceded by
the new keyword.
• Understand that this use of new is separate and distinct
from its use when creating an object instance.
class A {
public int i = 0;
class B : A {
new int i;
public B(int b) {

}

i = b;

public void Show() {
Console.WriteLine("i in derived class: " + i);
}}
class NameH {
static void Main() {
B ob = new B(2);
ob.Show();
}}

}
Access a Hidden Name
• using System;
• class A { public int i = 0;
}
• class B : A {
• new int i;
• public B(int a, int b) {
•
base.i = a; // this uncovers the i in A
•
i = b;
// i in B
• }
public void Show() {
Console.WriteLine("i in base class: " + base.i);
Console.WriteLine("i in derived class: " + i);
}}
class UncoverName {
static void Main() {
B ob = new B(1, 2);
ob.Show();
}}
Hidden Method
class A { public int i = 0;
public void Show() {
Console.WriteLine("i in base class: " + i);
}}
class B : A {
new int i;
public B(int a, int b) {
base.i = a;
i = b;
}
new public void Show() {
base.Show(); // this calls Show() in A
// this displays the i in B

Console.WriteLine("i in derived class: " + i);
}}
class UncoverName {
static void Main() {
B ob = new B(1, 2);
ob.Show();
}}
Overridden method
• Polymorphism is essential to object-oriented
programming for one reason: It allows a
general class to specify methods that will
be common to all of its derivatives, while
allowing derived classes to define the
specific implementation of some or all of
those methods.
• Overridden methods are another way that C#
implements the “one interface, multiple
methods” aspect of polymorphism.
Virtual Methods and Overriding
• A virtual method is a method that is
declared as virtual in a base class.
• The defining characteristic of a virtual
method is that it can be redefined in one
or more derived classes.
• You declare a method as virtual inside a
base class by preceding its declaration
with the keyword virtual.
• When a virtual method is redefined by a
derived class, the override modifier is
used.
• Thus, the process of redefining a virtual
method inside a derived class is called
method overriding.
• When overriding a method, the name,
return type, and signature of the
overriding method must be the same as
the virtual method that is being overridden.
• Also, a virtual method cannot be specified
as static or abstract.
• Dynamic method dispatch is the
mechanism by which a call to an
overridden method is resolved at runtime,
rather than compile time.
• Dynamic method dispatch is important
because this is how C# implements
runtime polymorphism.
class Base {
public virtual void Who() {
Console.WriteLine("Who() in Base");
}}
class Derived1 : Base {
public override void Who() {
Console.WriteLine("Who() in Derived1");
}}
class Derived2 : Base {
public override void Who() {
Console.WriteLine("Who() in Derived2"); }}
class OverrideDemo {
static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base class reference
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who(); }}
• Inside the Main( ) method, objects of type
Base, Derived1, and Derived2 are
declared. Also,
• a reference of type Base, called
baseRef , is declared. The program then
assigns a reference to each type of object
to baseRef and uses that reference to call
Who( ).
• the version of Who( ) executed is
determined by the type of object being
referred to at the time of the call, not by
the class type of baseRef .
sealed
• class B {
• public virtual void MyMethod() { /* ... */ }
• }
• class D : B {
•

•

// This seals MyMethod() and prevents further overrides.

sealed public override void MyMethod() {
/* ... */ }}
• class X : D {
• // Error! MyMethod() is sealed!
• public override void MyMethod() { /* ...
*/ }}

More Related Content

What's hot

constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java pptkunal kishore
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2Abbas Ajmal
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh Anand
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructorVENNILAV6
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++Bhavik Vashi
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 

What's hot (20)

Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 

Similar to Constructor

CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptxsyedabbas594247
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
Constructors.16
Constructors.16Constructors.16
Constructors.16myrajendra
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
concepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptxconcepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptxurvashipundir04
 
UNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptxUNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptxurvashipundir04
 

Similar to Constructor (20)

Oops
OopsOops
Oops
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
C#2
C#2C#2
C#2
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Constructors.16
Constructors.16Constructors.16
Constructors.16
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
concepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptxconcepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptx
 
UNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptxUNIT3 on object oriented programming.pptx
UNIT3 on object oriented programming.pptx
 
25csharp
25csharp25csharp
25csharp
 

More from abhay singh (15)

Iso 27001
Iso 27001Iso 27001
Iso 27001
 
Web service
Web serviceWeb service
Web service
 
Unsafe
UnsafeUnsafe
Unsafe
 
Threading
ThreadingThreading
Threading
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Networking and socket
Networking and socketNetworking and socket
Networking and socket
 
Namespace
NamespaceNamespace
Namespace
 
Inheritance
InheritanceInheritance
Inheritance
 
Generic
GenericGeneric
Generic
 
Gdi
GdiGdi
Gdi
 
Exception
ExceptionException
Exception
 
Delegate
DelegateDelegate
Delegate
 
Collection
CollectionCollection
Collection
 
Ado
AdoAdo
Ado
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Recently uploaded

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Recently uploaded (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

Constructor

  • 1. Class • A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope.
  • 2. Objects • Objects are programming constructs that have data, behavior, and identity. Object data is contained in the fields, properties, and events of the object, and object behaviors are defined by the methods and interfaces of the object. • Objects have identity — two objects with the same set of data are not necessarily the same object. • Objects in C# are defined through classes and structs — these form the single blueprint from which all objects of that type operate.
  • 3. Constructor • A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. The general form of a constructor is shown here: access class-name(param-list) { // constructor code } • This constructor is called by new keyword when an object is created. For example, in the line • MyClass t1 = new MyClass();
  • 4. Parameterized Constructors/ Overloaded constructor • class MyClass { • public int x; • public MyClass(int i) { • x = i; • } • }
  • 5. Static Constructors • A constructor can also be specified as static. A static constructor is typically used to initialize features that apply to a class rather than an instance. Thus, it is used to initialize aspects of a class before any objects of the class are created. Here is a simple example: using System; class Cons { public static int alpha; public int beta; // A static constructor. static Cons() { alpha = 99; Console.WriteLine("Inside static constructor."); }
  • 6. • • • • • • • • • • • • • // An instance constructor. public Cons() { beta = 100; Console.WriteLine("Inside instance constructor."); } } class ConsDemo { static void Main() { Cons ob = new Cons(); Console.WriteLine("Cons.alpha: " + Cons.alpha); Console.WriteLine("ob.beta: " + ob.beta); } } • Here is the output: • • • • Inside static constructor. Inside instance constructor. Cons.alpha: 99 ob.beta: 100
  • 7. Static Classes • A class can be declared static. There are two key features of a static class. • First, no object of a static class can be created. • Second, a static class must contain only static members. A static class is created by modifying a class declaration with the keyword static, shown here: • static class Program • { • static void Main(string[] args) • { • Console.WriteLine("this is static class constructor"); • } • }
  • 8. Constructor Chaining • When working with overloaded constructors, it is sometimes useful for one constructor to invoke another. • In C#, this is accomplished by using another form of the this keyword. • When the constructor is executed, the overloaded constructor that matches the parameter list specified by parameter-list2is first executed. • Then, if there are any statements inside the original constructor, they are executed.
  • 9. • • • • • • • • • • • class Car { private string description; private uint nWheels; public Car(string model, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string model) : this(model, 4) {} • Car myCar = new Car(“Proton Persona”);
  • 10. Private Constructors • In C# there are no global methods or constants. You might find yourself creating small utility classes that exist only to hold static members. Setting aside whether this is a good design or not, if you create such a class you will not want any instances created. • You can prevent any instances from being created by creating a default constructor (one with no parameters) which does nothing, and which is marked private. With no public constructors, it will not be possible to create an instance of your class.
  • 11. readonly • You can create a read-only field in a class by declaring it as readonly. • A readonly field can be given a value only by using an initializer when it is declared or by assigning it a value within a constructor. • Once the value has been set, it can’t be changed outside the constructor. • Thus, a readonly field is a good way to create a fixed value that has its value set by a constructor.
  • 12. • • • • • • • • • • • • • using System; class MyClass { public static readonly int SIZE = 10; } class DemoReadOnly { static void Main() { int[] source = new int[MyClass.SIZE]; for(int i=0; i < MyClass.SIZE; i++) source[i] = i; // Give source some values. foreach(int i in source) Console.Write(i + " "); Console.WriteLine();
  • 13. Passing by Reference • C# provides the ref parameter modifier for passing value into a method by reference and the out modifier for those cases in which you want to pass in a ref variable without first initializing it. • The ref parameter modifier causes C# to create a call-by-reference, rather than a call-by-value. The ref modifier is specified when the method is declared and when it is called.
  • 14. Use ref class RefTest { // This method changes its argument. Notice the use of ref. public void Sqr(ref int i) { i = i * i; }} class RefDemo { static void Main() { RefTest ob = new RefTest(); int a = 10; Console.WriteLine("a before call: " + a); ob.Sqr(ref a); // notice the use of ref Console.WriteLine("a after call: " + a); } } output a before call: 10 a after call: 100
  • 15. Out • The out modifier removes the requirement that a reference parameter be initiailzed. • The parameters to GetTime( ), for example, provide no information to the method; they are simply a mechanism for getting information out of it. • Thus, by marking all three as out parameters, you eliminate the need to initialize them outside the method. • Within the called method the out parameters must be assigned a value before the method returns. Here are the altered parameter declarations for GetTime( ):
  • 16. • • • • • • • • • • • • • • • • class Decompose { public int GetParts(double n, out double frac) { int whole; whole = (int) n; frac = n - whole; // pass fractional part back through frac return whole; // return integer portion }} class UseOut { static void Main() { Decompose ob = new Decompose(); int i; double f; i = ob.GetParts(10.125, out f); Console.WriteLine("Integer portion is " + i); Console.WriteLine("Fractional part is " + f); }}
  • 17. Reference Parameter int theHour = 0; int theMinute = 0; int theSecond = 0; t.GetTime( ref theHour, ref theMinute, ref theSecond); Out Parameter public void GetTime(out int h, out int m, out int s) { h = Hour; m = Minute; s = Second; }
  • 18. Ref/ Out • Value types are passed into methods by value. Ref parameters are used to pass value types into a method by reference. This allows you to retrieve their modified value in the calling Programming C# method. • Out parameters are used only to return information from a method.
  • 19. Calling Base Class Constructors • A derived class can call a constructor defined in its base class by using an expanded form of the derived class’ constructor declaration and the base keyword. derived-constructor (parameter-list ) : base( arg-list ) { // body of constructor }
  • 20. • arg-list specifies any arguments needed by the constructor in the base class. • Notice the placement of the colon. class Program { public int i=0, j=0; public Program(int a, int b) { i = a; j = b; } public void show1() { Console.WriteLine(“Base class"+i+j); } }
  • 21. class D:Program { string s1; public D(string s, int a, int b): base(a, b) { s1 = s; } public void sh() { Console.WriteLine(s1+i+j); } static void Main(string[] args) { D d1 = new D(“Drive Class ", 5, 8); d1.sh();} }
  • 22.
  • 23. Name Hiding • It is possible for a derived class to define a member that has the same name as a member in its base class. • When this happens, the member in the base class is hidden within the derived class. • If your intent (goal or aim) is to hide a base class member, then to prevent warning, the derived class member must be preceded by the new keyword. • Understand that this use of new is separate and distinct from its use when creating an object instance.
  • 24. class A { public int i = 0; class B : A { new int i; public B(int b) { } i = b; public void Show() { Console.WriteLine("i in derived class: " + i); }} class NameH { static void Main() { B ob = new B(2); ob.Show(); }} }
  • 25. Access a Hidden Name • using System; • class A { public int i = 0; } • class B : A { • new int i; • public B(int a, int b) { • base.i = a; // this uncovers the i in A • i = b; // i in B • }
  • 26. public void Show() { Console.WriteLine("i in base class: " + base.i); Console.WriteLine("i in derived class: " + i); }} class UncoverName { static void Main() { B ob = new B(1, 2); ob.Show(); }}
  • 27. Hidden Method class A { public int i = 0; public void Show() { Console.WriteLine("i in base class: " + i); }} class B : A { new int i; public B(int a, int b) { base.i = a; i = b; }
  • 28. new public void Show() { base.Show(); // this calls Show() in A // this displays the i in B Console.WriteLine("i in derived class: " + i); }} class UncoverName { static void Main() { B ob = new B(1, 2); ob.Show(); }}
  • 29. Overridden method • Polymorphism is essential to object-oriented programming for one reason: It allows a general class to specify methods that will be common to all of its derivatives, while allowing derived classes to define the specific implementation of some or all of those methods. • Overridden methods are another way that C# implements the “one interface, multiple methods” aspect of polymorphism.
  • 30. Virtual Methods and Overriding • A virtual method is a method that is declared as virtual in a base class. • The defining characteristic of a virtual method is that it can be redefined in one or more derived classes. • You declare a method as virtual inside a base class by preceding its declaration with the keyword virtual. • When a virtual method is redefined by a derived class, the override modifier is used.
  • 31. • Thus, the process of redefining a virtual method inside a derived class is called method overriding. • When overriding a method, the name, return type, and signature of the overriding method must be the same as the virtual method that is being overridden. • Also, a virtual method cannot be specified as static or abstract.
  • 32. • Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at runtime, rather than compile time. • Dynamic method dispatch is important because this is how C# implements runtime polymorphism.
  • 33. class Base { public virtual void Who() { Console.WriteLine("Who() in Base"); }} class Derived1 : Base { public override void Who() { Console.WriteLine("Who() in Derived1"); }} class Derived2 : Base { public override void Who() { Console.WriteLine("Who() in Derived2"); }}
  • 34. class OverrideDemo { static void Main() { Base baseOb = new Base(); Derived1 dOb1 = new Derived1(); Derived2 dOb2 = new Derived2(); Base baseRef; // a base class reference baseRef = baseOb; baseRef.Who(); baseRef = dOb1; baseRef.Who(); baseRef = dOb2; baseRef.Who(); }}
  • 35.
  • 36. • Inside the Main( ) method, objects of type Base, Derived1, and Derived2 are declared. Also, • a reference of type Base, called baseRef , is declared. The program then assigns a reference to each type of object to baseRef and uses that reference to call Who( ). • the version of Who( ) executed is determined by the type of object being referred to at the time of the call, not by the class type of baseRef .
  • 37. sealed • class B { • public virtual void MyMethod() { /* ... */ } • } • class D : B { • • // This seals MyMethod() and prevents further overrides. sealed public override void MyMethod() { /* ... */ }} • class X : D { • // Error! MyMethod() is sealed! • public override void MyMethod() { /* ... */ }}