Download - Chapter03 Object Based Programming
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 1/71
Chapter 3: Object-Based
Programing
Hoang Anh [email protected]
HaNoi University of Technology
1
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 2/71
Microsoft
Overview
“Everything is an object! At least, that is the view
from inside the CLR and the C# programming language.
This is no surprise, because C# is, after all, an object-
oriented language. The objects that you create through
class definitions in C# have all the same capabilities as
the other predefined objects in the system…”
Apress-Accelerated C# 2008
2
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 3/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
3
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 4/71
Microsoft
Roadmap(2)
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
4
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 5/71
Microsoft
3.1. Introduction
Object orientation uses classes to encapsulate data( attributes) andmethods(behaviors)
Data members: member variables or instance variables
Methods: manipulate the data
Objects are instantiated from classes
Objects have the ability to hide their implementation from other objects( information hiding )
Some objects can communicate with one another across well-defined interfaces
Example:
The driver’s interface to a car includes steering wheel,accelerator pedal, brake pedal and gear shift…
5
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 6/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
6
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 7/71
Microsoft
3.2. Implimenting a Time Abstract
DataType with a class Classes in C# facilitate the creation of abstract data types(ADT),
hiding their implementation from clients
In procedural programming language: client code is dependent onimplementation details of the data used in the code, ADT’s eliminatethis problem.
Example:
Time1 class
Three in instance variables: hour, minute and second
A constructor: initialzes objects of Time1 class
Method SetTime(): sets the time
Method ToUniversalString(): returns a string in universal-time format Method ToStandardString(): returns a string in standard-time format
7
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 8/71
// Class Time1 maintains time in 24-hour format.using System;// Time1 class definition public class Time1 : Object{
private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59// Time1 constructor initializes instance variables to// zero to set default time to midnight public Time1(){
SetTime( 0, 0, 0 );}// Set new time value in 24-hour format. Perform validity// checks on the data. Set invalid values to zero. public void SetTime(
int hourValue, int minuteValue, int secondValue ){
hour = ( hourValue >= 0 && hourValue < 24 ) ?hourValue : 0;
minute = ( minuteValue >= 0 && minuteValue < 60 ) ? minuteValue : 0;
second = (secondValue >= 0 && secondValue < 60) ?secondValue : 0;} // end method SetTime// convert time to universal-time (24 hour) format string public string ToUniversalString(){
return String.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
}// convert time to standard-time (12 hour) format string public string ToStandardString(){
return String.Format("{0}:{1:D2}:{2:D2} {3}",((hour == 12 || hour == 0) ? 12 : hour % 12), minute, second, (hour < 12 ? "AM" : "PM"));
}} // end class Time1
Example
Class Time1
inherits from
class Object
Delicate the
body of class
Declare
variables
Member
Access
Modifiers
Constructor
Methods
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 9/71
// Demonstrating class Time1.using System;using System.Windows.Forms;// TimeTest1 uses creates and uses a Time1 objectclass TimeTest1
{// main entry point for applicationstatic void Main( string[] args ){
Time1 time = new Time1(); // calls Time1 constructorstring output;// assign string representation of time to outputoutput = "Initial universal time is: " +
time.ToUniversalString() +"\nInitial standard time is: " +time.ToStandardString();
// attempt valid time settingstime.SetTime( 13, 27, 6 );
// append new string representations of time to outputoutput += "\n\nUniversal time after SetTime is: " +time.ToUniversalString() +"\nStandard time after SetTime is: " +time.ToStandardString();
// attempt invalid time settingstime.SetTime( 99, 99, 99 );output += "\n\nAfter attempting invalid settings: " +
"\nUniversal time: " + time.ToUniversalString() +"\nStandard time: " + time.ToStandardString();
MessageBox.Show(output, "Testing Class Time1");
} // end method Main
} // end class TimeTest1
Example
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 10/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
10
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 11/71
Microsoft
3.3. Class Scope
A class’s instance variables and methods belong to thatclass’s scope
Class members are accessible to methods in that class’sscope and can be referenced by name
Acesses to class members outside:referenceName.memberName
Block scope: Variables declared in a method have block scope
If a block-scope variable has the same name to a class-scopevariable, the class-scope one is hiden( access to that one in themethod using keyword this and dot operator)
11
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 12/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members
3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
12
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 13/71
Microsoft
3.4. Controlling Access to Members
The visibility of the member is defined by accessibility
keyword
The most common accessibility
public : Public members are visible inside and outside of the
class
private: The visibility of private members is restricted to the
containing class
Property
Controls access to private data get and set properties
13
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 14/71
Microsoft
// Demonstrate compiler errors from attempt to access// private class members.
class RestrictedAccess
{
// main entry point for application
static void Main(string[] args)
{Time1 time = new Time1();
time.hour = 7;
time.minute = 15;
time.second = 30;
}
} // end class RestrictedAccess
14
Compiler errors
public class Time1 : Object
{
private int hour;
private int minute;
private int second;}
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 15/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members
3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
15
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 16/71
Microsoft
3.5. Initialize Class Objects: Constructors Are called when a class is first loaded by the CLR of an object is created
Set up the state of the object by initializing the fields to a desired predefined state
Constructor syntax:
accessibility modifier typename(parameterlist )
Have the same name of the class and never have a return type
Initialize the state of an object
Types of Constructor:• Static Constructor
• Instance Constructor
Called when an instance of a class is created
Can be overloaded
Default constructor:• If a class does not define any constructors, the compiler provides a default( no-argument)
constructor( no code and noparameters)• Can be provided by the programmer. Programmer-provided ones can have code in bodies
16
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 17/71
Microsoft
static Constructors
static constructors is used to initialize the values of static data when the value isn’tknown at comple time
A given class (or structure) may define only a single static constructor.
A static constructor does not take an access modifier and cannot take any
parameters.
A static constructor executes exactly one time, regardless of how many objects of thetype are created.
The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
The static constructor executes before any instance-level constructors.
17
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 18/71
Microsoft
class Car
{
// The 'state' of the Car.
public string petName;
public int currSpeed;
// A custom default constructor.
public Car()
{
petName = "Chuck";
currSpeed = 10;
}// Here, currSpeed will receive the
// default value of an int (zero).
public Car(string pn)
{
petName = pn;
}
// Let caller set the full 'state' of the Car.
public Car(string pn, int cs)
{
petName = pn;
currSpeed = cs;
}
..
}
18
A custom defaultconstructor
Instance Constructors
static void Main(string[] args)
{
// Make a Car called Chuck going 10 MPH.
Car chuck = new Car();
chuck.PrintState();
// Make a Car called Mary going 0 MPH.
Car mary = new Car("Mary");
mary.PrintState();
// Make a Car called Daisy going 75 MPH.
Car daisy = new Car("Daisy", 75);daisy.PrintState();
}
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 19/71
Microsoft
class SavingsAccount
{ public double currBalance;
public static double currInterestRate;
public SavingsAccount(double balance)
{
currBalance = balance;
}
// A static constructor.
static SavingsAccount(){
Console.WriteLine("In static ctor!");
currInterestRate = 0.04;
}
...
}
19
static Constructor
static Data
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 20/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
33. Class Scope
3.4. Controlling Access to Members
3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
20
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 21/71
Microsoft
3.6. Using Overloaded Constructors
Constructors can be overloaded
Overloaded constructors may be used to providedifferent ways to initialize objects of a class
Contructors overloading is the process of using the sameContructors name for multiple Contructors
The function resolution of overloaded constructors isdetermined by the parameters of the new statement
21
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 22/71
Microsoft
Note:
If multiple contractor match a contractor call, thecompiler picks the best match
If none matches exactly but some implicit conversion
can be done to match a contractor, then thecontractor is invoked with implicit conversion.
A constructor can call another constructor using the
this reference
22
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 23/71
Microsoft
using System;
namespace Donis.CSharpBook
{
public class Employee
{
public Employee(string _name)
{
name = _name;}
public Employee(string _first, string _last)
{
name = _first + " " + _last;
}
private string name = "";
}
public class Personnel
{
public static void Main(){
Employee bob = new Employee("Jim", "Wilson"); // 2 arg c'tor
}
}
}
23
Overloaded
Constructures
class Employee
{
public Employee()
: this("")
{
}
public Employee(string _name)
{
name = _name;
}public Employee(string _first, string _last)
: this(_first + " " + _last)
{
}
public void GetName()
{
Console.WriteLine(name);
}
private string name = "";
}
Call Employee(string _name)constructor
using the colon syntax
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 24/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members
3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
24
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 25/71
Microsoft
3.7. Properties
Used for strict control of access to the internal state of an object
Are get and set methods exposed as properties
Propertiy syntax:
Accessibility modifier type propertyname{ attributes get{getbody}
attributes set{setbody}} Example:
Neither method is called directly
Auto-Implemented Properties
C# 3.0 has a new feature called auto-implemented properties that
reduce this burden significantly.
25
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 26/71
using System;namespace Donis.CSharpBook{
public class Person
{ private int prop_age; public int age{
set {// perform validation prop_age=value;}
get { return prop_age; }}
}
class People{ public static void Main(){
Person bob = new Person(); bob.age = 30;
Console.WriteLine(bob.age);}
}
}
Example
age property
Set method
Call gets method
value keyword represents theimplied parameter
// use Auto-Implemented Properties
public class Employee
{
public string FullName { get; set; }
public string Id { get; set; }
}
Use Ato-ImplementedProerties
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 27/71
Microsoft
Read-only and write-only properties
Read-only property:
Offer only the get method and omit the set method
Write-only property:
Have a set only
Example:
• Password property ( write-only property)
27
public class SensitiveForm
{
private string prop_password;
public string password{
set
{
prop_password = value;
}
}
}
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 28/71
Microsoft
Roadmap
3.1. Introduction
3.2. Implementing a time Abstract DataType with a class
3.3. Class Scope
3.4. Controlling Access to Members
3.5. Initialize Class Objects: Constructors
3.6.Using Overloaded Constructors
3.7. Properties
3.8. Composition: Objects References as InstanceVariables of Other Classes
28
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 29/71
Microsoft
3.8. Composition: Objects References
as Instance Variables of Other Classes
One form of software reuse is composition, in which a
class has as members references to objects of other
classes.
Example:
29
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 30/71
Microsoft
Class Date int instance variables
month
day year
Constructor
public Date( int theMonth, int theDay, int theYear ) Method
ToDateString(): returns the string representation of a Date.
CheckDay()
Class Employee: is composed of two references of type string and two references of class Date
Instance variables firstName
lastName
birthDate
hireDate Methods:
ToEmployeeString(): returns a string containing the name of the Employee and thestring representations of the Employee’s birthDate and hireDate
Class CompositionTest : runs the application with method Main Code:
30
References to Date objects
E l
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 31/71
2 // Date class definition encapsulates month, day and year. 34 using System;5
6 // Date class definition 7 public class Date8 {9 private into month; // 1-12 10 private into day; // 1-31 based on month 11 private into year; // any year 1213 // constructor confirms proper value for month; 14 // call method Check Day to confirm proper 15 // value for day 16 public Date( into theMonth, into theDay, into theYear )
17 {18 // validate month 19 if ( theMonth > 0 && theMonth <= 12 )20 month = theMonth;2122 else 23 {24 month = 1;25 Console.WriteLine(26 "Month {0} invalid. Set to month 1.", theMonth );27 }
2829 year = theYear; // could validate year 30 day = Check Day( theDay ); // validate day 31 }32
Example
31
Constructor that receives the month, day andyear arguments. Arguments are validated; if
they are not valid, the corresponding member isset to a default value
E l (2)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 32/71
Example(2)
32
33 // utility method confirms proper day value
34 // based on month and year
35 private into Check Day( into test Day )
36 {
37 into[] daysPerMonth =38 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
39
40 // check if day in range for month
41 if ( test Day > 0 && test Day <= daysPerMonth[ month ] )
42 return test Day;
43
44 // check for leap year
45 if ( month == 2 && test Day == 29 &&
46 ( year % 400 == 0 ||
47 ( year % 4 == 0 && year % 100 != 0 ) ) )
48 return test Day;
49
50 Console.WriteLine(
51 "Day {0} invalid. Set to day 1.", test Day );
52
53 return 1; // leave object in consistent state
54 }
55
56 // return date string as month/day/year
57 public string ToDateString()
58 {
59 return month + "/" + day + "/" + year;
60 }
61
62 } // end class Date
Validate that thegiven month canhave a given day
number
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 33/71
Microsoft
1 2 // Employee class definition encapsulates employee's first name, 3 // last name, birth date and hire date. 45 using System;67 // Employee class definition 8 public class Employee9 {10 private string firstName;
11 private string lastName;12 private Date birthDate;13 private Date hireDate;1415 // constructor initializes name, birth date and hire date 16 public Employee( string first, string last,17 int birthMonth, int birthDay, int birthYear,18 int hireMonth, int hireDay, int hireYear )
19 {20 firstName = first;21 lastName = last;2223 // create new Date for Employee birth day 24 birthDate = new Date( birthMonth, birthDay, birthYear );25 hireDate = new Date( hireMonth, hireDay, hireYear );
26 }27
Two Date objects are membersof the Employee class
Constructor that initializes the employee’sname, birth date and hire date
Example(3)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 34/71
Microsoft
28 // convert Employee to String format 29 public string ToEmployeeString()30 {31 return lastName + ", " + firstName +32 " Hired: " + hireDate.ToDateString() +33 " Birthday: " + birthDate.ToDateString();
34 }3536 } // end class Employee
Example(4)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 35/71
Microsoft
1 2 // Demonstrate an object with member object reference. 34 using System;5 using System.Windows.Forms;67 // Composition class definition 8 class CompositionTest9 {
10 // main entry point for application 11 static void Main( string[] args )12 {13 Employee e =14 new Employee( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 );1516 MessageBox.Show( e.ToEmployeeString(),17 "Testing Class Employee" );1819 } // end method Main
2021 } // end class CompositionTest
Example(5)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 36/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
36
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 37/71
Microsoft
3.9. Using the this Reference
C# supplies a this key word that provides access to the
current class instance
Uses of this keyword
•Resolve scope ambiguity
• Arise when an incoming paramerter is named identically to a
data field of the type
• Design a class using technique termed constructor
chaining
• Helpful when declaring multiple constructors
Example:
37
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 38/71
Microsoft
Class Motorcycle
Instance variables
driverIntensity
Name Method
SetDriverName(string)
38
class Motorcycle
{
public int driverIntensity;
public string name;
public void SetDriverName(string name)
{ name = name; }...
}
Problem: Theimpementation of
SetDriverName()assigns theincomingparameter backto itself
public void SetDriverName(stringname)
{ this.name = name; }
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 39/71
class Motorcycle{
public int driverIntensity;
public string driverName;// Constructor chaining. public Motorcycle() {} public Motorcycle(int intensity): this(intensity, "") {} public Motorcycle(string name): this(0, name) {}// This is the 'master' constructor that does all the real
work. public Motorcycle(int intensity, string name)
{ if (intensity > 10){
intensity = 10;}driverIntensity = intensity;driverName = name;
}...
}
Example
Constructor chaining
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 40/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
40
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 41/71
Microsoft
3.10. Garbage Collection
One of the key facilities in the CLR is the garbagecollector
GC frees you from the burden of handling memoryallocation and deallocation
The execution environment handles the tracking of object references and distroys the object instances whenthey’re no longer use
Forcing a Garbage Collection: In some situations, it maybe beneficial to programmatically force a garbagecollection using GC.Collect()
41
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 42/71
Microsoft 42
static void Main(string[] args)
{
...
// Force a garbage collection and wait for // each object to be finalized.
GC.Collect();
GC.WaitForPendingFinalizers();
...
}
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 43/71
Microsoft
Finalizer( Destructor)
• Returns resources to the system
• Each class can contain only one destructor
• Name:
Is formed by preceding the class name with a ~ charater • Is an override of a virtual method on System.Object
• Has no return type, no access modifiers
• Not inherited
43
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 44/71
Microsoft
using System;
public class Base
{
~Base()
{
Console.WriteLine("Base.~Base()");
}
}
public class Derived : Base
{
~Derived()
{
Console.WriteLine("Derived.~Derived()");
}
}public class EntryPoint
{
static void Main()
{
Derived derived = new Derived();
}
}
44
Destructor of Base class
Destructor of Derived
class
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 45/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
45
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 46/71
Microsoft
3.11. static Class Members
A program contains only one copy of each of a class’s static
variables in memory
A static variable represents class-wide information
The declaration of a static member begins with the keyword static
A static variable can be initialized in its declaration Static members:
• static method
• static data
• static constructor
• static class
46
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 47/71
using System; public static class StaticClass{
public static void DoWork(){
++callCount;Console.WriteLine("StaticClass.DoWork()");
} public class NestedClass{
public NestedClass(){
Console.WriteLine("NestedClass.NestedClass()");}
} private static long callCount = 0; public static long CallCount{
get{
return callCount;}
}}
public static class EntryPoint{
static void Main(){
StaticClass.DoWork();// OOPS! Cannot do this!// StaticClass obj = new StaticClass();StaticClass.NestedClass nested =
new StaticClass.NestedClass();Console.WriteLine("CallCount = {0}",StaticClass.CallCount);
}}
Example
static class is a collection
of static membersand can not haveobject instancedfrom
constants and nestedtypes declared
within a static classare static by default
Can not do this
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 48/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
48
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 49/71
Microsoft
3.12.const and readonly Members
Constant Data
Read-Only Field
49
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 50/71
Microsoft
constant Data
const syntax: accessibility modifier const constname=initialization;
Are initialized at compile time using a constant
expression and cannot be modified at run time
50
public class ZClass
{
public const int fielda = 5,
fieldb = 15;
// Error public static int fieldd=15;
public const int fieldc = fieldd + 10;
}
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 51/71
Microsoft
readonly Field
A read-only field cannot be changed after the initial
assignment
The value assigned to a read-only field can be
determined at runtime
51
class MyMathClass
{
public readonly double PI;
public MyMathClass()
{
PI = 3.14;
}// Error!
public void ChangePI()
{ PI = 3.14444; }
}
class MyMathClass
{
// Read-only fields can be assigned in ctors,
// but nowhere else.
public readonly double PI;public MyMathClass()
{
PI = 3.14;
}
}
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 52/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
52
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 53/71
Microsoft
3.13. Indexers
Allow to treat an object instance as if it were an array
Are instance-based and work on a specific instance of an object of the defining class
Cannot pass the results of calling an indexer on anobject as an out or ref parameter to a method as with areal array
this[] syntax
53
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 54/71
Microsoft
// Add the indexer to the existing class definition.
public class PeopleCollection : IEnumerable
{ private ArrayList arPeople = new ArrayList();
// Custom indexer for this class.
public Person this[int index]
{
get { return (Person)arPeople[index]; }
set { arPeople.Insert(index, value); }
}
...}
54
static void UseGenericListOfPeople()
{
List<Person> myPeople = new List<Person>();
myPeople.Add(new Person("Lisa", "Simpson", 9));
myPeople.Add(new Person("Bart", "Simpson", 7));
// Change first person with indexer.
myPeople[0] = new Person("Maggie", "Simpson", 2);// Now obtain and display each item using indexer.
for (int i = 0; i < myPeople.Count; i++)
{
Console.WriteLine("Person number: {0}", i);
Console.WriteLine("Name: {0} {1}", myPeople[i].FirstName,
myPeople[i].LastName);
Console.WriteLine("Age: {0}", myPeople[i].Age);
Console.WriteLine();}
}
class Person
{
private string FirstName;
private string LastName;private int Age;
...
}
Indexer iscreatedusingthis[]
syntax
Using indexer to getvalue
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 55/71
Microsoft
Overloaded Indexer Methods
public sealed class DataTableCollection : InternalDataCollectionBase
{
...
// Overloaded indexers!
public DataTable this[string name] { get; }public DataTable this[string name, string tableNamespace] { get; }
public DataTable this[int index] { get; }
}
55
E l
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 56/71
5 using System;6 using System.Drawing;7 using System.Collections;8 using System.ComponentModel;9 using System.Windows.Forms;10 using System.Data;1112 // Box class definition represents a box with length,13 // width and height dimensions 14 public class Box15 {
16 private string[] names = { "length", "width", "height" };17 private double[] dimensions = new double[ 3 ];1819 // constructor 20 public Box( double length, double width, double height )21 {22 dimensions[ 0 ] = length;23 dimensions[ 1 ] = width;24 dimensions[ 2 ] = height;
25 }2627 // access dimensions by index number 28 public double this[ int index ]29 {30 get 31 {32 return ( index < 0 || index > dimensions.Length ) ?33 -1 : dimensions[ index ];
34 }35
Indexer declaration; indexer receives an integer to specify which
dimension is wanted
The get index accessor
If the index requested is out bounds, return – 1; otherwireturn the appropriate eleme
Example
Example(2)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 57/71
36 set 37 {38 if ( index >= 0 && index < dimensions.Length )39 dimensions[ index ] = value;40 }4142 } // end numeric indexer 4344 // access dimensions by their names 45 public double this[ string name ]46 {47 get
48 {49 // locate element to get 50 int i = 0;5152 while ( i < names.Length &&53 name.ToLower() != names[ i ] )54 i++;5556 return ( i == names.Length ) ? -1 : dimensions[ i ];
57 }5859 set 60 {61 // locate element to set 62 int i = 0;6364 while ( i < names.Length &&65 name.ToLower() != names[ i ] )
66 i++;
Indexer that takes the name of thedimension as an argument
The set accessor for the index
Validate that the user wishes to set a validindex in the array and then set it
Example(2)
E l (3)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 58/71
68 if ( i != names.Length )69 dimensions[ i ] = value;70 }71
72 } // end indexer 7374 } // end class Box 7576 // Class IndexerTest 77 public class IndexerTest : System.Windows.Forms.Form 78 {79 private System.Windows.Forms.Label indexLabel;80 private System.Windows.Forms.Label nameLabel;81
82 private System.Windows.Forms.TextBox indexTextBox;83 private System.Windows.Forms.TextBox valueTextBox;8485 private System.Windows.Forms.Button nameSetButton;86 private System.Windows.Forms.Button nameGetButton;8788 private System.Windows.Forms.Button intSetButton;89 private System.Windows.Forms.Button intGetButton;9091 private System.Windows.Forms.TextBox resultTextBox;9293 // required designer variable 94 private System.ComponentModel.Container components = null;9596 private Box box;9798 // constructor 99 public IndexerTest()100 {
101 // required for Windows Form Designer support 102 InitializeComponent();
Example(3)
Example(4)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 59/71
104 // create block 105 box = new Box( 0.0, 0.0, 0.0 );106 }107108 // Visual Studio .NET generated code 109110 // main entry point for application 111 [STAThread]112 static void Main()113 {114 Application.Run( new IndexerTest() );115 }116117 // display value at specified index number 118 private void ShowValueAtIndex( string prefix, int index )119 {120 resultTextBox.Text =121 prefix + "box[ " + index + " ] = " + box[ index ];122 }123124 // display value with specified name 125 private void ShowValueAtIndex( string prefix, string name )126 {127 resultTextBox.Text =128 prefix + "box[ " + name + " ] = " + box[ name ];129 }130131 // clear indexTextBox and valueTextBox 132 private void ClearTextBoxes()133 {134 indexTextBox.Text = "";135 valueTextBox.Text = "";136 }137
Use the get accessor of the indexer
Use the set accessor of the indexer
Example(4)
Example(5)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 60/71
138 // get value at specified index 139 private void intGetButton_Click(140 object sender, System.EventArgs e )141 {
142 ShowValueAtIndex(143 "get: ", Int32.Parse( indexTextBox.Text ) );144 ClearTextBoxes();145 }146147 // set value at specified index 148 private void intSetButton_Click(149 object sender, System.EventArgs e )150 {151 int index = Int32.Parse( indexTextBox.Text );
152 box[ index ] = Double.Parse( valueTextBox.Text );153154 ShowValueAtIndex( "set: ", index );155 ClearTextBoxes();156 }157158 // get value with specified name 159 private void nameGetButton_Click(160 object sender, System.EventArgs e )161 {162 ShowValueAtIndex( "get: ", indexTextBox.Text );163 ClearTextBoxes();164 }165
Use integer indexer to set value
Use integer indexer to get value
Use string indexer to get value
Example(5)
E l (6)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 61/71
Microsoft
166 // set value with specified name 167 private void nameSetButton_Click(168 object sender, System.EventArgs e )
169 {170 box[ indexTextBox.Text ] =171 Double.Parse( valueTextBox.Text );172173 ShowValueAtIndex( "set: ", indexTextBox.Text );174 ClearTextBoxes();175 }176177 } // end class IndexerTest
Before setting value by index number
After setting value by index number
Example(6)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 62/71
Microsoft
Before getting value by dimension name
After getting value by dimension name
Before setting value by dimension name
Example(8)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 63/71
Microsoft
After setting value by dimension name
Before getting value by index number
After getting value by index number
Example(9)
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 64/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
64
3 14 D t Ab t ti d I f ti
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 65/71
Microsoft
3.14. Data Abstraction and Information
Hiding Classes normally hide the details of their implementation
from their clients
Data Abstraction: Example: stack, queue
Abstract Data Type (ADT): the programming-languagescommunity needed to formalize some notions about data
Data representation
Operation
Example:
int is an abstract representation of an integer
65
Information hiding
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 66/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
66
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 67/71
Microsoft
3.15. Software Reusability
Framework Class Library (FCL):
Contain thousands of predefined classes
Allow to achieve software reusability across platforms that
support
Enable C# developers to build applications faster by reusing
preexisting, extensively tested classes
Include classes for creating Web services
67
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 68/71
Microsoft
Roadmap
3.9. Using the this Reference
3.10. Garbage Collection
3.11. static Class Members
3.12. const and readonly Members 3.13. Indexers
3.14. Data Abstaction and Information Hiding
3.15. Software Reusability
3.16. Namespace and Assemplies
68
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 69/71
Microsoft
3.16. Namespaces and Assembly
Namespace helps to solve naming collision problems
Reusing class definitions between programs
public class can be reused from class libraries
Non- public classes can be used only by other classed in the
same assemply
A dynamic link library represents an assembly
When a project uses a class library, it must contain a
reference to the assembly that defines the class library
69
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 70/71
Microsoft
3.16. Namespaces and Assembly(2)
Orthogonal concepts:
namespace for organization
assembly for packaging
One namespace could be spread across multiple
assemblies
One assembly may contain multiple namesspaces
e.g. mscorlib.dll
70
7/27/2019 Chapter03 Object Based Programming
http://slidepdf.com/reader/full/chapter03-object-based-programming 71/71
Summary
You’ve learned the basic knowledge of object-oriented
programming in C#, including the use of classes and
their members.
You’ve also informed about garbage collection in C#,
how to use information hiding as well as data abstractionin C#