Sunteți pe pagina 1din 29

The C# Classes 1

C# 30

C# 3.0
Chapter 4 The C# Classes

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 2

C# 30

A C# Class Example
In the next
ne t slides,
slides youll
o ll find an e
example
ample of
Employee.
p y
Read it!
a C# class: Employee
What seems to be similar to a C++ class definition?
What seems to be different?

Later, youll find a small program using


this class: EmployeeApp
EmployeeApp. Read it!
Is there anything new in this small program?
List all your discoveries, understandings and questions

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 3

C# 30

The Employee Example


usingSystem;
namespaceEmployeeClass
namespace
EmployeeClass
{
publicclassEmployee
{
privatestring_name;
privatefloat_salary;
//Thefollowingfieldisstatic,meaningthatitis
//sharedacrossallinstancesoftheEmployeeclass.
=6000
6000.
.0f;
staticprivatefloat
p
_minimumSalary
y =
;

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 4

C# 30

The Employee Example


publicEmployee(stringname
publicEmployee(stringname,floatsalary){
floatsalary){
this._salary =salary;
}
publicEmployee(stringname)
:this(name,_minimumSalary
:this(name,_minimumSalary){}
){}
publicstringName{get{return_name;}}
publicfloatSalary{get{return_salary;}}
publicvoidWork(){
Console.WriteLine("Employee{0}isworking...",
_name);
);
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 5

C# 30

The Employee Example


publicvoidRaiseSalary
publicvoidRaiseSalary(
(int percentage){
_salary+=_salary*percentage/100
_salary+=_salary*percentage/100;
;
}
publicstaticvoidRaiseMinimumSalary
publicstaticvoidRaiseMinimumSalary(
(int percentage){
_minimumSalary
y +=_minimumSalary
minimumSalary*percentage/
y*percentage/100
p
g /100;
;
}
publicfloatCalculateSalary
publicfloatCalculateSalary(){
(){
if(_salary<_minimumSalary
if(_salary<_minimumSalary)
)
_salary=_
_salary=_minimumSalary
salary= minimumSalary;
minimumSalary;
return_salary;
}
}//endclass

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 6

C# 30

The Employee Example


classEmployeeApp
class
EmployeeApp {
staticEmployeeApp
static
EmployeeApp(){}
(){}
staticvoidMain(string[]args
staticvoidMain(string[]args){
){
Employeejack=newEmployee("JackSmith",6000
Employeejack=newEmployee("JackSmith",6000.
.0f);
Employeemary
p y
mary
y =newEmployee("MaryWhite",
=newEmployee("MaryWhite",7000
p y (
y
, 7000f);
f);
);
Employee
jack.Work();
jack.Work
();
mary.Work();
mary.Work
();
mary.RaiseSalary(
mary.RaiseSalary
(5);
Console
Console.WriteLine
Console.WriteLine(
WriteLine(
WriteLine("Jack'ssalary:"+
("Jack'ssalary:"+
Jack ssalary: +
jack.CalculateSalary());
jack.CalculateSalary
());
Console.WriteLine("Mary'ssalary:"+
Console.WriteLine
l
it i ("
("Mary'ssalary:"+
'
l
"
mary.CalculateSalary());
mary.CalculateSalary
());
}}}//endMain,endclass,endnamespace
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 7

C# 30

Access Modifiers
C# access modifiers
Accessibility

Meaning

public

Access is not restricted.

protected

Access is limited to the containing class or


types derived from the containing class.

internal

Access is limited to the current assembly


(project).
(project)

private

Access is limited to the containing type.

In addition, the protected internal access


modifier combination can be used
Meaning that access is limited to the current project or types
derived from the containing class

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 8

C# 30

Top-Level Classes Accessibility


A top-level
top le el class can be defined onl
only as
public or internal
Its default accessibility is: internal

To enable general use,


use a class must be
defined as public
internal accessibility should be used for helper
classes used by
y a class, that should not be exposed
p
to the general public

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 9

C# 30

Class Members Accessibility


Class members can be defined to ha
have
e
y level required
q
anyy accessibility
The default class member accessibility is: private
private.

The only limit is that a class member


accessibility level cannot be higher than its
containing class accessibility level
In such a case, the member accessibility level is
red ced to suit
reduced
s it class accessibilit
accessibility le
level
el

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 10

C# 30

Nested Types and Accessibility


Like in C++
C++, you
o can define within
ithin a C#
yp
class also a nested type
Class, structure, enum, delegate or interface
Nested types are useful for encapsulating
implementation details of a type
E.g.
E g an enumerator over a collection

Nested types accessibility rules are similar


to those of member types
Unlike C++ a nested type have an access to its
wrapper types private state

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 11

C# 30

C# Class Member Types


A Class is a user-defined
ser defined reference ttype
pe
A class may contain a rich set of member types:

Fields
Constants
Methods
Constructors
Finalizer
Properties
Indexers
Operators
Events
E
t

Throughout the course,


features new to C# 3.0 are
marked with the following
icon:

The first five basic member types will be discussed in this


chapter
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 12

C# 30

Fields Initialization
A field is what
hat we
e kno
know from C++ as a
data member
By default, class fields are initialized with a default
value according to their type category

Null for reference-types


yp
Zero or false for value-types

In C# we can provide fields with an initial value within


their definition
privateint minimumSalary =8000;
privatereadonly
p
y DateTime startDate =DateTime.Now;
;
privatePointposition=newPoint();

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 13

C# 30

Constructors
Like in C++:
The constructor is a special method bearing the
class name and must not return any value
A class constructor is activated before an instance of
the class is created
It should be used to provide the instance fields with
appropriate initial values

Th
The constructor
constructor
t
t s initialization
i iti li ti list
li t in
i C#
is used differently:
y
It cannot be used for fields initialization
It can be used only for other constructors
constructors activation:
The class base constructor
Another constructor in the class
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 14

C# 30

Constructors Example
classEmployee
{
publicEmployee(stringname,int salary)
{
_name=name;
a e
a e;
_salary=salary;
}
publicEmployee(stringname)
:this(name,_minimumSalary)
{
}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 15

C# 30

Instance vs
vs. Static Fields
B
By default,
defa lt a field is defined to be an
instance field:
A field that is contained in every instance of the class,
holding an instance
instancess specific value

A field can be defined to be a static filed:


A static field has a single copy in the application
domain, shared by all class instances
Static fields are defined using the keyword: static
Unlike C++,, public
p
static fields can be accessed only
y
through the class name

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 16

C# 30

Static Constructors
Static constructor is automatically created
to contain a simple static field initialization
The class author can explicitly define such a
constructor

Static constructors do not take any


parameters
Their signature should be composed of the static
modifier, followed by class name with no parameters:
staticSomeClass()
staticSomeClass
()
{
//Staticdatainitialization
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 17

C# 30

Constants
A constant is a field that remains constant
throughout the applications lifetime
A constant is defined using the keyword: const
A constant field is always static

A constant must be assigned a value in


the declaration
The constant value must be a value that can be
computed at compile-time
Limits the constant possible types only to built-in types that
can be assigned
with literals
g
privateconststringcompanyName ="GreatCompany";
publicconstdoublePI=3.1415
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 18

C# 30

Read-Only
Read
Only Fields
The constant field features might sometimes be
insufficient
We might want to define an unchangeable field that its value
cannot be computed at compile-time
We may also require this non-changeable field to be an instance
fi ld and
field
d nott a static
t ti fi
field
ld

In such a case, we should define the field as a


read-only
d l fi
field
ld
A read-only field is defined with: readonly
Its
It value
l can be
b sett only
l once att its
it declaration,
d l ti
or in
i th
the
constructor
Initialized at run-time,, a read-onlyy field can be of anyy type
yp
privatereadonly DateTime startDate =DateTime.Now;

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 19

C# 30

Properties
Properties can be considered as smart
fields
They enable defining special get and set methods,
termed getter and setter
These methods can be activated with the simple field
access syntax

This way, we can provide the users with


an intuitive
a
u e field
e d access se
service,
ce, ye
yet sstill
perform validation (and any other required)
operations

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 20

C# 30

Properties Example
classDate{
publicDate(int
publicDate(
int day,int
day,int month,int
month,int year)...
publicint
public
int Day
{
get
get{return
{ etu
_day;
day;}
day;}
set{
(IsDayOK
y
(
))
if
if(
(value))
_day=value;
_day
=value;
}
}
}
//Usage:
Dated=newDate(...);
Console.WriteLine(
Console.WriteLine
(d.Day);
d.Day);
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 21

C# 30

Properties: Behind the Scenes


.method publichidebysig specialname instanceint32
get Day() cil managed
get_Day()
{
//Codesize11(0xb)
.maxstack 1
.locals([0]int32CS$00000003$00000000)
IL_0000:ldarg.0
IL_0001:ldfld
int32Date::day
y
IL_000a:ret
}//endofmethodDate::get_Day
}
g _ y

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 22

C# 30

Property Accessibility
By default,
default the accessibility of the set and
the get accessors is provided by the
property definition
An accessors accessibility level can be explicitly
changed to a more restrictive one
publicFieldType PropertyName
{
get
{
returnfield;
}
protectedset
{
field=value;
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 23

C# 30

Automatic Properties
Trivial
automatically
Tri ial properties can be a
tomaticall
field
backed byy a compiler-generated
p
g
publicclassEmployee{
publicstringName{get;set;}
publicint
bli i
Id{get;set;}
d {
}
}

Accessibility
A
ibilit can be
b specified
ifi d as well:
ll
publicclassEmployee{
...
publicfloatCommission{get;internal set;}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 24

C# 30

Methods
Class member ffunctions
nctions are termed
termed:
methods
In C#, all methods are defined inside the class
Class methods can access other class members
publicvoidraiseSalary(int percentage)
{
salary+=salary*percentage/100;
}

The object on which the method was activated is


accessed inside a method using the keyword: this

Methods can be overloaded based on name and parameters

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 25

C# 30

Static Functions
Functions
F nctions that manipulate
manip late static fields onl
only
Static methods can be activated through class name
only
Theyy have no access to anyy non-static
classEmployee{
publicstaticvoidraiseMinimumSalary(int percentage)
{
minimumSalary +=minimumSalary *percentage/100;
}
privatestaticint minimumSalary =6000;
}
staticvoidMain(){
Employee.raiseMinimumSalary(5);
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 26

C# 30

Static Class
A class can be declared as static b
by using
sing
y
in the class definition
the static keyword
It is not possible to create instances of a static class

Static classes are loaded automatically


When the program or namespace containing the
class is loaded

Static classes are sealed


Therefore cant be inherited by any type

The only constructor permitted in a static


class is the static constructor
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 27

C# 30

Static Class
A static
t ti class
l
cant
t have
h
non-static
t ti
methods
There are several situations where
static classes are useful:
Wh
When group off methods
th d provide
id global
l b l functionality
f
ti
lit
A singleton pattern can be implemented by using a
static class
We need a type that represents a bunch of P/Invoke
methods

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 28

C# 30

Static Class Example


publicstaticclassUtilities{
publicstaticPointScreenResolution
publicstaticPoint
ScreenResolution
{
get{returnscreenResolution
get{returnscreenResolution;}
;}
}
publicstaticstringGetUserGroupName
publicstaticstringGetUserGroupName(string
(stringuserName
userName)
)
{...}
publicstaticstring[]LocalDrivesLetters
publicstaticstring[]LocalDrivesLetters {...}
privatestaticPointscreenResolution
privatestaticPointscreenResolution;
;
}
//Main
if(Utilities.ScreenResolution
if(
Utilities.ScreenResolution ==newPoint(800
==newPoint(800,
,600
600))
))
{
...
}
Console.WriteLine(
Console.WriteLine
(Utilities.GetUserGroupName
Utilities.GetUserGroupName("Mary"));
("Mary"));
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 29

C# 30

Extension Methods
Challenges:
Challenges
How do you add functionality to a sealed class?
How do you add functionality to an interface without
changing
g g it or its implementors?
p

Static methods are the canonical solution


staticint ToInt(strings){
staticint
ToInt(strings){
returnint.Parse
return
int.Parse(s);
(s);
}

Extension methods offer syntactic sugar:


staticint ToInt(
staticint
ToInt(this strings){
returnint.Parse
return
int.Parse(s);
(s);
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 30

C# 30

Whats
What s The Difference?
Discoverability
Disco erabilit
Intellisense support

Natural (fluent) syntax


Instead
I t d of:
f
int i =Utilities.ToInt
=Utilities.ToInt(s);
(s);

We can write:
int i =s.ToInt
=s.ToInt();
();

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 31

C# 30

Extension Methods Notes


Inter
Inter-assembly
assembl calls work
ork d
due
e to the
[Extension]
[
] attribute
The this keyword is not compiled into IL

Limitations:
Extension methods can access public members only
Extension methods can live in static classes only
To use an extension method, its namespace must be
imported (usingMyExtensions;)

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

The C# Classes 32

Use Extensions with Caution!


E
Extensions
tensions from different namespaces can
collide
Instance methods are always preferred to
extension
t
i methods
th d
Extension methods from the current namespace
p
are
preferred to methods from other namespaces

Beware of polluting the Intellisense


window with System.Object extensions

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 33

C# 30

The C# new Operator


All C# objects must be created using the
new operator
The new operator performs the full object creation
process. Specifically, it generates a call to the
constructor
Note that the new operator is not reserved for heap
(reference-type) objects only, but is also used for
proper value type object creation:
DateTime dt =newDateTime
=newDateTime(
(1,1,2000
2000,
,0,0,0);

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 34

C# 30

The C# new Operator


The onl
only e
exceptions
ceptions are some .NET
NET
primitive types
p
yp
These objects can be assigned using the assignment
operator (rather then the new operator):
Primitive types:
int i =
=5
5;

Strings and Arrays which can also simply initialized:


strings="HelloWorld";
int[]
int
[]iarr
iarr = {1,2,3};

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 35

C# 30

Object Initializers
Settable properties often replace
g
to object
j
constructors with regard
initialization
iti li
t
Obj
Objectt iinitializer
syntax:
//Insteadof:
Personp=newPerson();
p.Id =2
=2;
p.Name =JohnDoe;
JohnDoe ;
Personp=newPerson{
Id=2
Id=
2,
Name=JohnDoe
};

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 36

C# 30

Object Initializers
Its possible to in
invoke
oke constr
constructors
ctors with
ith
parameters:
p
Personp=newPerson(
Personp=newPerson(2) {
Name=JohnDoe
};

Note that some properties have severe


side effects (e.g.
FileSystemWatcher.Enabled)

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 37

C# 30

Chapter 4 Exercise 1

THE RECTANGLE EXERCISE

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 38

C# 30

Partial Types
A partial ttype
pe can be split o
over
er ttwo
o or
more source files
There are several situations where
splitting
litti a ttype iis desirable:
d i bl
When working
g with wizards that change
g or add code
to existing one

This can be done in a separate file in order to isolate the


automatically generated code from our code

When generating dynamic code

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 39

C# 30

The partial Keyword


Use the partial keyword to create a
partial type
Indicates that other parts of the type can be defined
within the namespace and in different files
//MapControl
//
//MapControl.cs
MapControl.cs
MapControl cs
public partialclassMapControl
partialclassMapControl :UserControl
:UserControl
{
publicMapControl
public
MapControl()
()
{
InitializeComponent();
InitializeComponent
();
}
protectedoverridevoid
protectedoverridevoidOnPaint
OnPaint(...){...}
(...){...}
}
//MapControl.Designer.cs
//MapControl.Designer.cs
p
g
partialclassMapControl
partialclassMapControl :UserControl
:UserControl {...}
{
(){...}
privatevoidInitializeComponent
privatevoidInitializeComponent(){...}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 40

C# 30

Parts

All p
parts must use the p
partial keyword
y
All parts must be available at compile time
All parts must have the same accessibility
If any of the parts are declared abstract
The entire type is considered abstract

If any of the parts are declared sealed


The entire type is considered sealed

If any of the parts declare a base type


The entire type inherits that class

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 41

C# 30

Parts
Parts can specif
specify different base interfaces
The final type implements all of the interfaces listed
by all of the partial declarations

Any member declared in a partial definition


Is available to all of the other parts

The final type is the combination of all the


parts at compile time
The partial modifier is not available on
delegate or enum declarations
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 42

C# 30

Merging All Together


If any
an of the following
follo ing are declared in the
parts, the final type
yp will include all:
various p

XML comments
Interfaces
Generic-type parameter attributes
Cl
Class
attributes
tt ib t
Members

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 43

C# 30

Example
//MapControl.cs
//MapControl.cs
partialclassMapControl
partialclassMapControl :IMapConsumer
:IMapConsumer
{...}
//M
//MapControl.g.cs
//
M C t l
MapControl.g.cs
partialclassMapControl
partialclassMapControl :UserControl
:UserControl
{...}
//MapControl.Designer.cs
//
MapControl.Designer.cs
[MapComponent]
MapComponent]
partialclassMapControl
partialclass
ti l l
MapControl
M
M C t l {...}
{
}
//Mergedresultingtype:
[MapComponent]
MapComponent]
partialclassMapControl
partialclassMapControl :UserControl
:UserControl,
,IMapConsumer
IMapConsumer
{
}
{...}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 44

C# 30

Partial Methods
Working with
designer-generated
ith designer
generated classes

Designer (e.g. Visual Studio) spits out a class


We cant modify it changes will be lost
We dont
don t want to derive from it too expensive
If we dont extend it we want zero cost

This suggests
gg
a compile-time
p
mechanism

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 45

C# 30

Partial Methods
//InButton.generated.cs
//InButton
generated cs
publicsealedpartialclassButton{
publicvoidClick(){
OnClicking();
//Dosomework
OnClicked();
}
partialvoidOnClicking();
partialvoidOnClicked();
}
//InButton.mycode.cs
partialclassButton{
partialvoidOnClicking(){
//Mycustomizedwork
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 46

C# 30

Partial Methods Notes


Partial methods are al
always
a s private
pri ate and
cannot return values
This is an intra-assembly mechanism
Partial methods cant
can t be defined in another assembly

Best performance:
No virtual call, no derivation, no delegates

Weak customization:
Intra-assembly, compile-time only
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 47

C# 30

Parameter Types
By default
default, method parameters in C# are
passed by value
When the parameter is of a value-type, a local copy of
the arguments value is created for the method
W
Working
ki on this
hi llocall iindependent
d
d
values
l
copy, the
h method
h d
has no influence on the original arguments value

When the parameter is of a reference-type


reference-type, a local
copy of the arguments reference is created for the
method
Through this reference copy the method can alter the original
arguments value, however, it cannot change the reference
itself

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 48

C# 30

Reference Parameters
C# pro
provides
ides us
s with
ith a special kind of
parameter: reference p
p
parameters
This is the same as passing the address of the
variable in C, or reference in C++
C

Reference parameters are defined by


adding
ddi th
the ref
f keyword
k
db
before
f
th
the
parameter type in the method
methods
s signature
The ref keyword must also be specified in the
method call

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 49

C# 30

Reference Parameters Example


usingSystem;
classUtil
class
Util {
//Thisclearlydoesntwork
staticpublicvoidSwap(int
staticpublicvoidSwap(int i1,int
,int i2){
int tmp =i1
=i1;
i1
1=i
=i2
i2;
i2=
2=tmp
tmp;
;
}
staticpublicvoidSwap(ref
staticpublicvoidSwap(ref int i1,ref
,ref int i2){
int tmp
p =i
=i1
1;
i1=i
1=i2
2;
i2=
2=tmp
tmp;
;
}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 50

C# 30

Reference Parameters Example


classUtilApp {
classUtilApp
staticvoidMain(){
int i1
1=
=5
5,i
,i2
2=
2
=10
10
10;
;
Console.WriteLine("i
Console.WriteLine
("i1
1={
={0
0}i2
}i2={
={1
1}",i1
}",i1,i2
,i2);
Util.Swap
Ut
Util.Swap(i
.S ap(
ap(
(i1
1,
,i2
,i
2);
Console.WriteLine("i
Console.WriteLine
("i1
1={
={0
0}i2
}i2={
={1
1}",i1
}",i1,i2
,i2);
p(ref i1,
Util.Swap
Util.Swap(
,ref
,
ref i2);
Console.WriteLine("i
Console.WriteLine
("i1
1={
={0
0}i2
}i2={
={1
1}",i1
}",i1,i2
,i2);
}
}
i1=
1=5
5 i2=
2=10
10
i1=
1= 5 i2=
2=10
10
i1=
1= 10i
10i2=
2=5
5
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 51

C# 30

Output Parameters
Sometime we need to initialize parameter
in a method
C# does not let us use an uninitialized parameter
Trying to use ref will result a compilation error
Therefore we should use the out keyword
staticDictionary<int,
staticDictionary<int
int,int
int>_cache=
int>
int
>
>_cache=
cache=
newDictionary<int
newDictionary<
int,
,int
int>();
>();
staticvoidMain(string[]args
staticvoidMain(string[]args)
)
{
int value;
_cache.TryGetValue(
cache.TryGetValue(1,out
,out value);
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 52

C# 30

Parameters Array
A method can accept a variable number of
parameters
This is the equivalent to the ellipses () in C/C++
Use the params keyword, followed by an array
parameter definition
doubleAverage(params
g (
double[]numbers)...
)

The arguments are received by the method as an


array
The array can be processed using standard array
methods

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 53

C# 30

Parameters Array Example


classUtilApp {
classUtilApp
staticvoidMain(){
C
Console.WriteLine(
Console.WriteLine
l W it Li (Utils.Average
Util A
Utils.Average(
(2,
,2
2.2,
,2
2.7));
))
}
}
classUtils
class
Utils {
publicstaticdoubleAverage(
p
publicstaticdoubleAverage(params
g (p
(p
params double[]numbers){
[]
) {
doublesum=0
doublesum=
0;
for(int
for(
int i =0
=0;i
;i <numbers.Length
<numbers.Length;
;i
i++)
sum+=numbers[i
sum+=numbers[
i];
returnsum/
returnsum/numbers.Length
numbers.Length;
;
}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 54

C# 30

The Main() Method


Every C# program must have a Main()
It serves as the entry point of the program
The programs control starts and ends in Main()
The Main() method must be defined inside a class
or a struct
It has to be a static method

Note the capitalized M !


Main() may return either void or int
values

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 55

C# 30

The Main() Method


The Main() method can accept
arguments in an array of strings
This can be used to get command line arguments
staticvoidMain(string[]args)
{
foreach (stringarg inargs)
Console WriteLine (arg);
Console.WriteLine
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 56

C# 30

What About the Destructor?


As we
e have
ha e alread
already seen in the
y
j
members discussion,
System.Object
.NET sort of supports the concept of a
destructor
The destructor discussion is actually part of a wider
and central .NET general topic:
Managed environment and garbage collection

The next chapter dives deep into this very


topic
p
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 57

C# 30

Chapter 4 Exercise 2

THE LINKED LIST EXERCISE

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The C# Classes 58

C# 30

Chapter Summary
The C# class
C# access modifiers
Class members
Methods,, Properties,
p
, Constructors,, Constant & Readonlyy

Static members, class & constructors


Partial types and methods

Passing parameters by ref & out


Variable parameters array
The
Th M
Main()
i () method
th d
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel