SlideShare a Scribd company logo
1 of 25
Creating and Destroying
Objects
Overview
 Using Constructors
 Initializing Data
 Objects and Memory
 Resource Management
Using Constructors
 Creating Objects
 Using the Default Constructor
 Overriding the Default Constructor
 Overloading Constructors
Creating Objects
 Step 1: Allocating memory
 Use new keyword to allocate memory from the heap
 Step 2: Initializing the object by using a constructor
 Use the name of the class followed by parentheses
Date when = new Date( );
Using the Default Constructor
 Features of a default constructor
 Public accessibility
 Same name as the class
 No return type—not even void
 Expects no arguments
 Initializes all fields to zero, false or null
 Constructor syntax
class Date { public Date( ) { ... } }
Overriding the Default
Constructor
 The default constructor might be inappropriate
 If so, do not use it; write your own!
class Date
{
public Date( )
{
ccyy = 1970;
mm = 1;
dd = 1;
}
private int ccyy, mm, dd;
}
Overloading Constructors
 Constructors are methods and can be overloaded
 Same scope, same name, different parameters
 Allows objects to be initialized in different ways
 WARNING
 If you write a constructor for a class, the compiler does not
create a default constructor
class Date
{
public Date( ) { ... }
public Date(int year, int month, int day) { ... }
...
}
Initializing Data
 Using Initializer Lists
 Declaring Readonly Variables and Constants
 Initializing Readonly Fields
 Declaring a Constructor for a Struct
 Using Private Constructors
 Using Static Constructors
Using Initializer Lists
 Overloaded constructors might contain duplicate code
 Refactor by making constructors call each other
 Use the this keyword in an initializer list
class Date
{
...
public Date( ) : this(1970, 1, 1) { }
public Date(int year, int month, int day) { ... }
}
 Value of constant field is
obtained at compile time
 Value of readonly
field is obtained at
run time
Declaring Readonly Variables and
Constants
Initializing Readonly Fields
 Readonly fields must be initialized
 Implicitly to zero, false or null
 Explicitly at their declaration in a variable initializer
 Explicitly inside an instance constructor
class SourceFile
{
private readonly ArrayList lines;
}
Declaring a Constructor for a
Struct
 The compiler
 Always generates a default constructor. Default constructors
automatically initialize all fields to zero.
 The programmer
 Can declare constructors with one or more arguments.
Declared constructors do not automatically initialize fields to
zero.
 Can never declare a default constructor.
 Can never declare a protected constructor.
Using Private Constructors
 A private constructor prevents unwanted objects from
being created
 Instance methods cannot be called
 Static methods can be called
 A useful way of implementing procedural functions
public class Math
{
public static double Cos(double x) { ... }
public static double Sin(double x) { ... }
private Math( ) { }
}
Using Static Constructors
 Purpose
 Called by the class loader at run time
 Can be used to initialize static fields
 Guaranteed to be called before instance constructor
 Restrictions
 Cannot be called
 Cannot have an access modifier
 Must be parameterless
Objects and Memory
 Object Lifetime
 Objects and Scope
 Garbage Collection
Object Lifetime
 Creating objects
 You allocate memory by using new
 You initialize an object in that memory by using a
constructor
 Using objects
 You call methods
 Destroying objects
 The object is converted back into memory
 The memory is de-allocated
Objects and Scope
 The lifetime of a local value is tied to the scope in which
it is declared
 Short lifetime (typically)
 Deterministic creation and destruction
 The lifetime of a dynamic object is not tied to its scope
 A longer lifetime
 A non-deterministic destruction
Garbage Collection
 You cannot explicitly destroy objects
 C# does not have an opposite of new (such as delete)
 This is because an explicit delete function is a prime source
of errors in other languages
 Garbage collection destroys objects for you
 It finds unreachable objects and destroys them for you
 It finalizes them back to raw unused heap memory
 It typically does this when memory becomes low
Resource Management
 Object Cleanup
 Writing Destructors
 Warnings About Destructor Timing
 IDisposable Interface and Dispose Method
 The using Statement in C#
Object Cleanup
 The final actions of different objects will be different
 They cannot be determined by garbage collection.
 Objects in .NET Framework have a Finalize method.
 If present, garbage collection will call destructor before
reclaiming the raw memory.
 In C#, implement a destructor to write cleanup code. You
cannot call or override Object.Finalize.
Writing Destructors
 A destructor is the mechanism for cleanup
 It has its own syntax:
 - No access modifier
 - No return type, not even void
 - Same name as name of class with leading ~
 - No parameters
class SourceFile
{
~SourceFile( ) { ... }
}
Warnings About Destructor
Timing
 The order and timing of destruction is undefined
 Not necessarily the reverse of construction
 Destructors are guaranteed to be called
 Cannot rely on timing
 Avoid destructors if possible
 Performance costs
 Complexity
 Delay of memory resource release
IDisposable Interface and Dispose
Method
 To reclaim a resource:
 Inherit from IDisposable Interface and implement Dispose
method that releases resources
 Call GC.SuppressFinalize method
 Ensure that calling Dispose more than once is benign
 Ensure that you do not try to use a reclaimed resource
The using Statement in C#
 Syntax
 Dispose is automatically called at the end of the using
block
using (Resource r1 = new Resource( ))
{
r1.Method( );
}
Review
 Using Constructors
 Initializing Data
 Objects and Memory
 Resource Management

More Related Content

What's hot

C questions
C questionsC questions
C questionsparm112
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructorsuraj pandey
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop Samad Qazi
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And PatternsAnil Bapat
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.pptKarthik Sekar
 
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
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Effective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it EffectiveEffective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it EffectiveC4Media
 
Hibernate training
Hibernate trainingHibernate training
Hibernate trainingTechFerry
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementAnil Bapat
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design PatternJaswant Singh
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NETBlackRabbitCoder
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6BlackRabbitCoder
 

What's hot (20)

C questions
C questionsC questions
C questions
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
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
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And Patterns
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
 
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
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Effective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it EffectiveEffective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it Effective
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Hibernate training
Hibernate trainingHibernate training
Hibernate training
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
C++
C++C++
C++
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6
 

Similar to Module 10 : creating and destroying objects

Similar to Module 10 : creating and destroying objects (20)

C++
C++C++
C++
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
7494609
74946097494609
7494609
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
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++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
[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
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
C#ppt
C#pptC#ppt
C#ppt
 
Objective c
Objective cObjective c
Objective c
 
Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 

More from Prem Kumar Badri

Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexersPrem Kumar Badri
 
Module 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopeModule 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopePrem Kumar Badri
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and eventsPrem Kumar Badri
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variablesPrem Kumar Badri
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsPrem Kumar Badri
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingPrem Kumar Badri
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsPrem Kumar Badri
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parametersPrem Kumar Badri
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variablesPrem Kumar Badri
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformPrem Kumar Badri
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collectionPrem Kumar Badri
 

More from Prem Kumar Badri (20)

Module 15 attributes
Module 15 attributesModule 15 attributes
Module 15 attributes
 
Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexers
 
Module 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopeModule 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scope
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and events
 
Module 11 : Inheritance
Module 11 : InheritanceModule 11 : Inheritance
Module 11 : Inheritance
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variables
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and generics
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented Programming
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & Exceptions
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variables
 
Module 2: Overview of c#
Module 2:  Overview of c#Module 2:  Overview of c#
Module 2: Overview of c#
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET Platform
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
C# Multi threading
C# Multi threadingC# Multi threading
C# Multi threading
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
C# Generic collections
C# Generic collectionsC# Generic collections
C# Generic collections
 
C# Global Assembly Cache
C# Global Assembly CacheC# Global Assembly Cache
C# Global Assembly Cache
 

Recently uploaded

भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

Module 10 : creating and destroying objects

  • 2. Overview  Using Constructors  Initializing Data  Objects and Memory  Resource Management
  • 3. Using Constructors  Creating Objects  Using the Default Constructor  Overriding the Default Constructor  Overloading Constructors
  • 4. Creating Objects  Step 1: Allocating memory  Use new keyword to allocate memory from the heap  Step 2: Initializing the object by using a constructor  Use the name of the class followed by parentheses Date when = new Date( );
  • 5. Using the Default Constructor  Features of a default constructor  Public accessibility  Same name as the class  No return type—not even void  Expects no arguments  Initializes all fields to zero, false or null  Constructor syntax class Date { public Date( ) { ... } }
  • 6. Overriding the Default Constructor  The default constructor might be inappropriate  If so, do not use it; write your own! class Date { public Date( ) { ccyy = 1970; mm = 1; dd = 1; } private int ccyy, mm, dd; }
  • 7. Overloading Constructors  Constructors are methods and can be overloaded  Same scope, same name, different parameters  Allows objects to be initialized in different ways  WARNING  If you write a constructor for a class, the compiler does not create a default constructor class Date { public Date( ) { ... } public Date(int year, int month, int day) { ... } ... }
  • 8. Initializing Data  Using Initializer Lists  Declaring Readonly Variables and Constants  Initializing Readonly Fields  Declaring a Constructor for a Struct  Using Private Constructors  Using Static Constructors
  • 9. Using Initializer Lists  Overloaded constructors might contain duplicate code  Refactor by making constructors call each other  Use the this keyword in an initializer list class Date { ... public Date( ) : this(1970, 1, 1) { } public Date(int year, int month, int day) { ... } }
  • 10.  Value of constant field is obtained at compile time  Value of readonly field is obtained at run time Declaring Readonly Variables and Constants
  • 11. Initializing Readonly Fields  Readonly fields must be initialized  Implicitly to zero, false or null  Explicitly at their declaration in a variable initializer  Explicitly inside an instance constructor class SourceFile { private readonly ArrayList lines; }
  • 12. Declaring a Constructor for a Struct  The compiler  Always generates a default constructor. Default constructors automatically initialize all fields to zero.  The programmer  Can declare constructors with one or more arguments. Declared constructors do not automatically initialize fields to zero.  Can never declare a default constructor.  Can never declare a protected constructor.
  • 13. Using Private Constructors  A private constructor prevents unwanted objects from being created  Instance methods cannot be called  Static methods can be called  A useful way of implementing procedural functions public class Math { public static double Cos(double x) { ... } public static double Sin(double x) { ... } private Math( ) { } }
  • 14. Using Static Constructors  Purpose  Called by the class loader at run time  Can be used to initialize static fields  Guaranteed to be called before instance constructor  Restrictions  Cannot be called  Cannot have an access modifier  Must be parameterless
  • 15. Objects and Memory  Object Lifetime  Objects and Scope  Garbage Collection
  • 16. Object Lifetime  Creating objects  You allocate memory by using new  You initialize an object in that memory by using a constructor  Using objects  You call methods  Destroying objects  The object is converted back into memory  The memory is de-allocated
  • 17. Objects and Scope  The lifetime of a local value is tied to the scope in which it is declared  Short lifetime (typically)  Deterministic creation and destruction  The lifetime of a dynamic object is not tied to its scope  A longer lifetime  A non-deterministic destruction
  • 18. Garbage Collection  You cannot explicitly destroy objects  C# does not have an opposite of new (such as delete)  This is because an explicit delete function is a prime source of errors in other languages  Garbage collection destroys objects for you  It finds unreachable objects and destroys them for you  It finalizes them back to raw unused heap memory  It typically does this when memory becomes low
  • 19. Resource Management  Object Cleanup  Writing Destructors  Warnings About Destructor Timing  IDisposable Interface and Dispose Method  The using Statement in C#
  • 20. Object Cleanup  The final actions of different objects will be different  They cannot be determined by garbage collection.  Objects in .NET Framework have a Finalize method.  If present, garbage collection will call destructor before reclaiming the raw memory.  In C#, implement a destructor to write cleanup code. You cannot call or override Object.Finalize.
  • 21. Writing Destructors  A destructor is the mechanism for cleanup  It has its own syntax:  - No access modifier  - No return type, not even void  - Same name as name of class with leading ~  - No parameters class SourceFile { ~SourceFile( ) { ... } }
  • 22. Warnings About Destructor Timing  The order and timing of destruction is undefined  Not necessarily the reverse of construction  Destructors are guaranteed to be called  Cannot rely on timing  Avoid destructors if possible  Performance costs  Complexity  Delay of memory resource release
  • 23. IDisposable Interface and Dispose Method  To reclaim a resource:  Inherit from IDisposable Interface and implement Dispose method that releases resources  Call GC.SuppressFinalize method  Ensure that calling Dispose more than once is benign  Ensure that you do not try to use a reclaimed resource
  • 24. The using Statement in C#  Syntax  Dispose is automatically called at the end of the using block using (Resource r1 = new Resource( )) { r1.Method( ); }
  • 25. Review  Using Constructors  Initializing Data  Objects and Memory  Resource Management