csharp in detail part1
TRANSCRIPT
© { JSL }11
C#
in D
etai
lC
# in
Det
ail Jon Jagger
Software Trainer, Designer, Consultant
www.jaggersoft.com
jon@ jaggersoft.com
{ JSL }
Part 1Part 1
© { JSL }22
Bla
tan
t A
dve
rtB
lata
nt
Ad
vert
an interactive, friendly, expert instructoran interactive, friendly, expert instructor Jon has worked for Microsoft using C#Jon has worked for Microsoft using C#
lots of great exerciseslots of great exercises to make sure you understandto make sure you understand
even more slideseven more slides with detail, explanations, and rationaleswith detail, explanations, and rationales
full slide notesfull slide notes include careful comparisons with C++ and include careful comparisons with C++ and
JavaJava
C# in DetailC# in Detailis also available as anis also available as an
instructor led courseinstructor led course
© { JSL }33
Ag
end
aA
gen
da
overviewoverview built-in value typesbuilt-in value types enumsenums parametersparameters control flowcontrol flow structsstructs constructorsconstructors fieldsfields operatorsoperators indexersindexers propertiesproperties
© { JSL }44
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
Ove
rvie
wO
verv
iew
© { JSL }55
C#
Fea
ture
sC
# F
eatu
res
static typingstatic typing
runtime polymorphismruntime polymorphism
operator overloadingoperator overloading
exceptionsexceptions
multiple public realizationmultiple public realization
non deterministic finalizationnon deterministic finalization
multi threadingmulti threading
compile time polymorphism ?compile time polymorphism ?
value typesvalue types
garbage collectiongarbage collection
single public inheritancesingle public inheritance
unified type systemunified type system
Object super base classObject super base class
virtual execution systemvirtual execution system
reflectionreflection
reference typesreference types
C#, C++ and Java
C# and JavaC# and C++
C#
© { JSL }66
Hel
lo U
niv
erse
Hel
lo U
niv
erse
Hiker.cs
using System;
public class Hiker{ public static void Main() { int result; result = 9 * 6; int tirteen; tirteen = 13; Console.Write(result / tirteen); Console.Write(result % tirteen); }}
// An Irish program that find the answer // to life, the universe, and everything
C:\Sharp>csc Hiker.cs
C:\Sharp>Hiker.exe42//
single-line comment
© { JSL }77
MS
ILM
SIL
C:\Sharp>ildasm Hiker.exe
© { JSL }88
VE
SV
ES intermediate language, ILintermediate language, IL loading managed code including resolving namesloading managed code including resolving names conversion of IL into native codeconversion of IL into native code verification of the type safety of the ILverification of the type safety of the IL verification of integrity of the metadataverification of integrity of the metadata garbage collection servicesgarbage collection services initiation, propagation, and intercepting exceptionsinitiation, propagation, and intercepting exceptions profiling and debugging servicesprofiling and debugging services management of threads, contexts, and remotingmanagement of threads, contexts, and remoting
© { JSL }99
Fo
rty
Tw
oF
ort
y T
wo
C# programs are constructed from tokensC# programs are constructed from tokens
Hiker.cs
/*
*/
using System;
public class Hiker{ public static void Main() { int result; result = 9 * 6; int tirteen; tirteen = 13; Console.Write(result / tirteen); Console.Write(result % tirteen); }}
/* An Irish program that find the answer * to life, the universe, and everything */
multi-line comment
(non nestable)
© { JSL }1010
To
ken
sT
oke
ns
five kinds of tokens in C# programsfive kinds of tokens in C# programs
token examples
identifiers Hiker Main result
keywords public class int
literals 9 6 13
operators + - * / % =
punctuators ; { } ,
© { JSL }1111
Pre
-pro
cess
ing
Pre
-pro
cess
ing
C# has a sensibly limited "preprocessor"C# has a sensibly limited "preprocessor" no #include, no #pragmano #include, no #pragma #define, but no macros#define, but no macros
#undef PP_TOKEN
#if pp-expression
#line 42 "hhg.cs"
#error pp-msg#region pp-msg
#define PP_TOKEN
#elif pp-expression
#else
#endif
#warning pp-msg#endregion pp-msg
#if 0 #if false
© { JSL }1212
Iden
tifi
ers
Iden
tifi
ers
rulesrules made of letters and digitsmade of letters and digits must start with a lettermust start with a letter underscore is a letterunderscore is a letter case sensitivecase sensitive
recommendationsrecommendations don't use underscoresdon't use underscores don't abbreviatedon't abbreviate don't use hungariandon't use hungarian follow style guidelinesfollow style guidelines
differentDifferent
differentDifferent
answer4242Answer
answer4242Answer
rare_styleprivateStylePublicStyle
rare_styleprivateStylePublicStyle
msgmessage
msgmessage
!CLS
camelCase
PascalCase
© { JSL }1313
Key
wo
rds
Key
wo
rds
some identifiers have a fixed meaningsome identifiers have a fixed meaning
using System;
public class Hiker{ public static void Main() { int result; result = 9 * 6; int tirteen; tirteen = 13; Console.Write(result / tirteen); Console.Write(result % tirteen); }}
/* An Irish program that find the answer * to life, the universe, and everything */
© { JSL }1414
Key
wo
rd T
able
Key
wo
rd T
able
76 keywords (+ 5 ish)76 keywords (+ 5 ish)
abstract as base bool break byte case catch char checkedclass const continue decimal defaultdelegate do double else enumevent explicit extern false finally fixed float for foreach gotoif implicit in int interfaceinternal is lock long namespacenew null object operator outoverride params private protected public readonly ref return sbyte sealedshort sizeof stackalloc static stringstruct switch this throw truetry typeof uint ulong uncheckedunsafe ushort using virtual void while
abstract as base bool break byte case catch char checkedclass const continue decimal defaultdelegate do double else enumevent explicit extern false finally fixed float for foreach gotoif implicit in int interfaceinternal is lock long namespacenew null object operator outoverride params private protected public readonly ref return sbyte sealedshort sizeof stackalloc static stringstruct switch this throw truetry typeof uint ulong uncheckedunsafe ushort using virtual void while
get set valueadd remove
get set valueadd remove
These are sometimes reserved
Any keyword can be used as anidentifier if preceeded by @
© { JSL }1515
Lit
eral
sL
iter
als
some tokens represent fixed valuessome tokens represent fixed values
type literal
bool true false
double 3.1415
char 'X'
int 9 6 13 42
string "Hello"
truth
floating point
integers
characters
sequencesof characters
object nullnothing
© { JSL }1616
Op
erat
ors
Op
erat
ors
some tokens represent fixed actionssome tokens represent fixed actions
symbol category
+ - * / % arithmetic
&& || ! logical
< <= > >= relational
== != equality
= assignment
& | ^ ~ << >> bitwise
© { JSL }1717
Pu
nct
uat
ors
Pu
nct
uat
ors
some tokens group or separatesome tokens group or separate { and } form scoped blocks{ and } form scoped blocks semi-colons mark the end of a simple statementsemi-colons mark the end of a simple statement
using System;
public class Hiker{ public static void Main() { int result; result = 9 * 6; int tirteen; tirteen = 13; Console.Write(result / tirteen); Console.Write(result % tirteen); }}
© { JSL }1818
Dec
lara
tio
ns
Dec
lara
tio
ns
declarations introduce variables into a scopedeclarations introduce variables into a scope a variable has an identifier and a typea variable has an identifier and a type a variable's type can a variable's type can nevernever change change
using System;
public class Hiker{ public static void Main() { int result; result = 9 * 6; int tirteen; tirteen = 13; Console.Write(result / tirteen); Console.Write(result % tirteen); }}
type identifier ;type identifier ;
type identifier, another ;type identifier, another ;
© { JSL }1919
Exp
ress
ion
sE
xpre
ssio
ns
expressions compute things!expressions compute things! an expression yields a valuean expression yields a value an expression must also have a side-an expression must also have a side- effecteffect
using System;
public class Hiker{ public static void Main() { int result; result = 9 * 6; int tirteen; tirteen = 13; Console.Write(result / tirteen); Console.Write(result % tirteen); }}
© { JSL }2020
Tw
o T
ypes
Tw
o T
ypes
value typesvalue types variables contain their own data directlyvariables contain their own data directly local variables always live on the stacklocal variables always live on the stack
reference typesreference types variables refer to their data indirectlyvariables refer to their data indirectly local variables refer to objects on the heaplocal variables refer to objects on the heap
object
valueenum
class
interface
[ ]array
delegate
struct value
object
object
object
@
@
@
@
© { JSL }2121
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
bo
ol
bo
ol
© { JSL }2222
bo
ol
bo
ol boolbool is a keyword is a keyword
an alias for System.Booleanan alias for System.Boolean only values are only values are truetrue and and falsefalse
bool love = true;bool teeth = false;
System.Boolean love = true;System.Boolean teeth = false;
using System;...Boolean love = true;Boolean teeth = false;
Boolean love = true;Boolean teeth = false;
© { JSL }2323
Sys
tem
.Bo
ole
anS
yste
m.B
oo
lean
namespace System{ public struct Boolean ... { // static fields public static readonly string FalseString; public static readonly string TrueString; ... // static methods public static bool Parse(string); ... // instance methods public override string ToString(); ... }}
bool b = bool.Parse(Console.ReadLine());Console.WriteLine(true.ToString());Console.WriteLine(b.ToString());
© { JSL }2424
bo
ol O
per
ato
rsb
oo
l Op
erat
ors
int tens = 9 * 6 / 13;int units = 9 * 6 % 13;
bool isFour = tens == 4;bool isTwo = units == 2;
bool hhg;hhg = isFour && isTwo;hhg = !(isFour && isTwo);hhg = !isFour || !isTwo;hhg = !hhg;
assignment =
in - equality == !=
logical ! && || short circuiting
© { JSL }2525
bo
ol C
on
vers
ios
bo
ol C
on
vers
ios
no implicit conversions to no implicit conversions to boolbool everever nonenone nadanada zipzip under any circumstances whatsoeverunder any circumstances whatsoever
© { JSL }2626
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
byt
e sh
ort
int
lon
gb
yte
sho
rt in
t lo
ng
© { JSL }2727
Inte
ger
Typ
es
Inte
ger
Typ
es
type bits System.
short 16 Int16
int 32 Int32
long 64 Int64
sbyte 8* SByte
ushort 16 Uint16
uint 32 UInt32
ulong 64 UInt64
byte 8* Byte
CLS?
yes
yes
yes
no
no
no
no
yes
signed?
yes
yes
yes
yes
no
no
no
no
© { JSL }2828
Sys
tem
.Int3
2S
yste
m.In
t32
namespace System{ public struct Int32 ... { // static fields public const int MaxValue; public const int MinValue; ... // static methods public static int Parse(string); ... // instance methods public override string ToString(); ... }}
int i = 42;System.Int32 count = 0;Console.WriteLine(42.ToString());Console.WriteLine(count.ToString());Console.WriteLine(int.MaxValue);
© { JSL }2929
Inte
ger
Lit
eral
sIn
teg
er L
iter
als
decimal-integer-literal: decimal-digits integer-type-suffixopt
decimal-digits: decimal-digit decimal-digits decimal-digit
decimal-digit: one of 0 1 2 3 4 5 6 7 8 9
integer-type-suffix: one of U u L l UL Ul uL ul LU Lu lU lu
hexdecimal-integer-literal: 0x hex-digits integer-type-suffixopt
0X hex-digits integer-type-suffixopt
hex-digits: hex-digit hex-digits hex-digit
hex-digit: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
no octal
© { JSL }3030
Inte
ger
Op
erat
ors
Inte
ger
Op
erat
ors
assignment =
in- equality == !=
relational < > <= >=
arithmetic + - * / %
bitwise | & ^ ~
shift << >>
inc/dec ++ --
compoundassignment
© { JSL }3131
Pri
mar
y O
per
ato
rsP
rim
ary
Op
erat
ors
grouping (x)
access x.y
method call f(x)
indexing a[x]
post-increment x++
post-decrement x--
stack allocation stackalloc
constructor call new
type retrieval typeof
size retrieval sizeof
checking (un)checked
also -> (unsafe)
arrays only
unsafe
© { JSL }3232
Pre
ced
ence
Pre
ced
ence
primary see previous slide
unary + - ! ~ ++x –-x (T)x
multiplicative * / %
additive + -
shift << >>
relational < > <= >= is as
equality == !=
bitwise & ^ |
boolean && || ?:
assignment = *= /= %= += -= ...
© { JSL }3333
Ass
oci
ativ
ity
Ass
oci
ativ
ity
rule 1 rule 1 except for the assignment operators all binary except for the assignment operators all binary
operators are left-associativeoperators are left-associative
rule 2rule 2 the assignment operators and the conditional the assignment operators and the conditional
operator (?:) are right-associativeoperator (?:) are right-associative
x + y + z (x + y) + z
x = y = z x = (y = z)
© { JSL }3434
Eva
luat
ion
Ord
erE
valu
atio
n O
rder
operands are evaluated strictly left to rightoperands are evaluated strictly left to right same as in Java, unspecified in C++same as in Java, unspecified in C++
int m = 2;int answer = ++m * ++m + ++m * ++m;
3 * 4 + ++m * ++m
12 + ++m * ++m
12 + 5 * ++m
12 + 5 * 6
12 + 30
3 * ++m + ++m * ++m
42
© { JSL }3535
Inte
ger
Ove
rflo
wIn
teg
er O
verf
low
DivideByZeroException, OverflowExceptionDivideByZeroException, OverflowException un/checked expressionsun/checked expressions un/checked { statementsun/checked { statementsoptopt } }
int m = int.Parse(Console.ReadLine());
Func(checked(m * 2));m = checked(m * 2);checked { F(m * 2); m *= 2;}
Func(m * 2);m *= 2;
Func(unchecked(m * 2));m = unchecked(m * 2);unchecked { F(m * 2); m *= 2;}
always checked
never checked
csc /checked+ *.cscsc /checked- *.cs
© { JSL }3636
Inte
ger
MS
ILIn
teg
er M
SIL
integer MSIL instructions come in two formsinteger MSIL instructions come in two forms one checks for overflow ( eg mul.ovf )one checks for overflow ( eg mul.ovf ) one doesn'one doesn' t check for overflow ( eg mul )t check for overflow ( eg mul )
int a, b, c;...
.locals(int32 V0, int32 V1, int32 V2)
int c = checked(a * b);
ldloc.0ldloc.1mul.ovfstloc.2
int c = a * b;ldloc.0ldloc.1mulstloc.2
C# MSIL
© { JSL }3737
Inte
ger
Sh
ifti
ng
Inte
ger
Sh
ifti
ng
never throw exceptionsnever throw exceptions (u)int shift (u)int shift count & 0x1F count & 0x1F (u)long shift (u)long shift count & 0x3F count & 0x3F
int operator <<( int x, int count); long operator <<( long x, int count); uint operator <<( uint x, int count);ulong operator <<(ulong x, int count);
int operator >>( int x, int count); long operator >>( long x, int count);
uint operator >>( uint x, int count);ulong operator >>(ulong x, int count);
arithmetic shift
logical shift
MSIL == shl
MSIL == shr and shr.un
© { JSL }3838
Inte
ger
Co
nve
rsio
ns
Inte
ger
Co
nve
rsio
ns
implicit, widening conversionsimplicit, widening conversions never lose information, never throw exceptionnever lose information, never throw exception
explicit narrowing conversions (casts)explicit narrowing conversions (casts) may lose information, may throw exceptionmay lose information, may throw exception
short s;int m;
.locals(int16 V0, int32 V1)
ldloc.1conv.ovf.i2stloc.0
ldloc.1conv.i2stloc.0
s = checked((short)m);
s = unchecked((short)m);
s = (short)m; ??csc /checked+ csc /checked-
C# IL
© { JSL }3939
sbyte
short
int
longsb
yte
sho
rt
int
lon
g
byt
e
ush
ort
uin
t
ulo
ng
byte
ushort
uint
ulong
signed unsigned
sig
ne
du
nsi
gn
ed
fromtoo
Co
nve
rsio
n T
able
Co
nve
rsio
n T
able
•• II II II
EE •• II II
EE EE •• II
EE EE EE ••
EE EE EE EE
EE EE EE EE
EE EE EE EE
EE EE EE EE
EE II II II
EE EE II II
EE EE EE II
EE EE EE EE
•• II II II
EE •• II II
EE EE •• II
EE EE EE ••
© { JSL }4040
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
flo
at d
ou
ble
flo
at d
ou
ble
© { JSL }4141
F.P
. Typ
es
F.P
. Typ
es
type
bits
System.
float
32
Single
double
64
Double
CLS
sig. figs 157
yes yes
MSIL float32 float64
± 3.4x1038 ± 1.7x10308range
suffix F f D d
© { JSL }4242
Sys
tem
.Do
ub
leS
yste
m.D
ou
ble
namespace System{ public struct Double ... { // static fields public const double Epsilon; public const double MaxValue; public const double MinValue; public const double NaN; public const double NegativeInfinity; public const double PositiveInfinity; ... // static methods public static bool IsInfinity(double); public static bool IsNaN(double); public static double Parse(string); ... // instance methods public override string ToString(); ... }}
© { JSL }4343
F.P
. Lit
eral
sF
.P. L
iter
als
real-literal: digits . digits exponentopt suffixopt
. digits exponentopt suffixopt
digits exponent suffixopt digits suffix
digits: digit digits digit
digit: one of 0 1 2 3 4 5 6 7 8 9
exponent: e signopt digits E signopt digits
sign: one of + -
suffix: one of F f D d M m
Truth(1.2E-3D is double);Truth(.89F is System.Single);Truth(123D is double);
OK(123D.ToString());OK(123.0.ToString());OK(123.ToString());
Fails(123.);Fails(123.D);Fails(123..ToString());
compile time errors
© { JSL }4444
F.P
. Op
erat
ors
F.P
. Op
erat
ors
mostly the same as the integersmostly the same as the integers modulus % is permitted (it's not in C++)modulus % is permitted (it's not in C++) shift operators are not permittedshift operators are not permitted
FP arithmetic never throws exceptionsFP arithmetic never throws exceptions result too small result too small +/- zero +/- zero result too large result too large +/- infinity +/- infinity invalid operation invalid operation NaN NaN either operand NaN either operand NaN Nan Nan
© { JSL }4545
F.P
. Co
nve
rsio
ns
F.P
. Co
nve
rsio
ns
double double float float explicit conversionexplicit conversion never throwsnever throws
integer integer floating point floating point implicit conversionimplicit conversion never throwsnever throws may lose precision, never loses magnitudemay lose precision, never loses magnitude
floating point floating point integer integer explicit conversionexplicit conversion may throw OverflowException (Beta-2 language may throw OverflowException (Beta-2 language
specification says it won't)specification says it won't)
© { JSL }4646
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
dec
imal
dec
imal
© { JSL }4747
dec
imal
Typ
e
dec
imal
Typ
e
type
bits
System.
decimal
128
Decimal
CLS
sig. figs 28
yes
± 7.9x1028range
suffix M m
float
32
double
64
157
..x1038 ..x10308
F f D d
DoubleSingle
yesyes
© { JSL }4848
Sys
tem
.Dec
imal
Sys
tem
.Dec
imal
namespace System{ public struct Decimal ... { // static fields public static readonly decimal MaxValue; public static readonly decimal MinusOne; public static readonly decimal MinValue; public static readonly decimal One; public static readonly decimal Zero; ... // static methods public static decimal Parse(string); ... // instance methods public override string ToString(); public double ToDouble(); ... }}
© { JSL }4949
mo
re C
on
vers
ion
sm
ore
Co
nve
rsio
ns
float / double float / double decimal decimal explicit conversion (FP have greater range)explicit conversion (FP have greater range) always checked, may throwalways checked, may throw
decimal decimal float / double float / double explicit conversion (FP has less precision)explicit conversion (FP has less precision) never throws, may lose precisionnever throws, may lose precision
decimal decimal integral integral explicit conversion (decimal has greater range)explicit conversion (decimal has greater range) always checked, may throw OverflowExceptionalways checked, may throw OverflowException
integral integral decimal decimal implicit conversionimplicit conversion never throws, never loses informationnever throws, never loses information
© { JSL }5050
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
char
char
© { JSL }5151
char
Typ
ech
ar T
ype
type
bits
System.
char
16
Char
CLS yes
0x0000
0xFFFF
min
max
Unicode 3.0
You idiot, that's a You idiot, that's a chairchair
© { JSL }5252
Sys
tem
.Ch
arS
yste
m.C
har
namespace System{ public struct Char ... { // static fields public const char MaxValue; public const char MinValue; ... // static methods public static bool IsDigit(char); public static bool IsLetter(char); public static bool IsWhiteSpace(char); public static string ToString(char); ... // instance methods public override string ToString(); ... }}
© { JSL }5353
char
Lit
eral
sch
ar L
iter
als
character-literal: ' character '
character: single-character simple-escape-character hex-escape-sequence unicode-escape-sequence
single-character: any char except ' (U+0027), \ (U+005C), and new-line
simple-escape-character: one of \' \" \\ \0 \a \b \f \n \r \t \v
hex-escape-sequence: \x xdigit xdigiitopt xdigitopt xdigitopt
xdigit: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
unicode-escape-sequence: \u xdigit xdigit xdigit xdigit \U xdigit xdigit xdigit xdigit xdigit xdigit xdigit xdigit
no octalescape
© { JSL }5454
char
Co
nve
rsio
ns
char
Co
nve
rsio
ns
char is classified as an integral typechar is classified as an integral type you can do char arithmetic you can do char arithmetic
implicit conversion from char toimplicit conversion from char to ushort, int, uint, long, ulong, float, double, ushort, int, uint, long, ulong, float, double,
decimaldecimal
explicit conversion from char toexplicit conversion from char to sbyte, byte, shortsbyte, byte, short
no implicit conversions to charno implicit conversions to char even for sbyte, byte, and shorteven for sbyte, byte, and short
© { JSL }5555
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
enu
men
um
© { JSL }5656
enu
m D
ecla
rati
on
enu
m D
ecla
rati
on
a user-a user- declared declared valuevalue-- typetype
enum Suit{ Clubs, Diamonds, Hearts, Spades};
class Example{ static void Main() { ... Suit dig = Spades; ... Suit trumps = Suit.Clubs; ... }}
each enum declaration creates a new declaration space
optional semi-colon
compiletimeerror
okay
© { JSL }5757
enu
m N
ote
sen
um
No
tes
enum Suit : int { Clubs, Diamonds, Hearts = 42, Spades, }
the underlying integer typecan be any of the basic 8 integertypes and defaults to int (not char)
named constants can be initalizedfrom constants; they default to the previousconstant + 1
optional comma afterlast named constant
© { JSL }5858
enu
m U
seen
um
Use
enumenums implicitly derive from System.Enums implicitly derive from System.Enum
Suit trumps = Suit.Club;string[] names = System.Enum.GetNames(trumps.GetType());...Console.Write(names[0]); // ClubsConsole.Write(trumps); // ClubsConsole.Write("{0}", trumps); // ClubsConsole.Write(trumps.ToString()); // ClubsConsole.Write((Suit)42); // 42
namespace System{ public class Enum ... { // static methods public static string[] GetNames(Type); ... // instance methods public override string ToString(); // constructor protected Enum(); }}
© { JSL }5959
enu
m O
per
ato
rsen
um
Op
erat
ors
enumenum variables can mostly be used as variables can mostly be used as intintss
assignment =
in- equality == !=
relational < > <= >=
arithmetic + - * / %
bitwise | & ^ ~
shift << >>
inc/dec ++ --
yes
yes
yes
yes
no
yes
yes
© { JSL }6060
enu
m C
on
vers
ion
sen
um
Co
nve
rsio
ns
implicit conversionimplicit conversion literal 0 to any literal 0 to any enumenum type type
explicit conversionsexplicit conversions from from enumenum to to enumenum via underlying type via underlying type from from enumenum to numeric type (including to numeric type (including charchar)) from numeric type (including from numeric type (including charchar) to ) to enumenum
The set of values that an enum can take onThe set of values that an enum can take onis not limited by its enum members. Anyis not limited by its enum members. Anyvalue of the underlying type of the enumvalue of the underlying type of the enumcan be cast to the enum type, and is acan be cast to the enum type, and is adistinct, valid value of that type. distinct, valid value of that type.
The set of values that an enum can take onThe set of values that an enum can take onis not limited by its enum members. Anyis not limited by its enum members. Anyvalue of the underlying type of the enumvalue of the underlying type of the enumcan be cast to the enum type, and is acan be cast to the enum type, and is adistinct, valid value of that type. distinct, valid value of that type.
C# language spec (0.26)
© { JSL }6161
Ter
min
olo
gy
Ter
min
olo
gy
two kinds of two kinds of valuevalue type type enumenum types types structstruct types types
two kinds of two kinds of structstruct types types user-defined user-defined structstruct type type
no literal syntaxno literal syntax simplesimple structstruct types types
integral types ( includes integral types ( includes char char )) floating point types ( includes floating point types ( includes decimal decimal )) boolbool
© { JSL }6262
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
Par
amet
ers
Par
amet
ers
© { JSL }6363
Co
py
Par
amet
ers
Co
py
Par
amet
ers
a plain parameter is a a plain parameter is a copycopy of the argument of the argument no frills bitwise copyno frills bitwise copy the argument must be definitely assignedthe argument must be definitely assigned argument can be an "rvalue"argument can be an "rvalue"
static void Method(Suit parameter){ parameter = Suit.Hearts;}
static void Main(){ Suit arg = Suit.Clubs; Console.Write(arg); Method(arg); Console.Write(arg);}
ClubsClubs
© { JSL }6464
ref
Par
amet
ers
ref
Par
amet
ers
a a refref parameter is an parameter is an aliasalias for the argument for the argument no copy takes placeno copy takes place argument must be definitely assignedargument must be definitely assigned argument must be an "lvalue"argument must be an "lvalue" refref required on argument required on argument andand parameter parameter
static void Method(ref Suit parameter){ parameter = Suit.Hearts;}
static void Main(){ Suit arg = Suit.Clubs; Console.Write(arg); Method(ref arg); Console.Write(arg);}
ClubsHearts
© { JSL }6565
ou
t P
aram
eter
so
ut
Par
amet
ers
an an outout parameter is an parameter is an aliasalias for the argument for the argument no copy takes placesno copy takes places argument need noargument need no t be definitely assigned t be definitely assigned parameter must be definitely assignedparameter must be definitely assigned argument must be an "lvalue"argument must be an "lvalue" outout required on argument required on argument andand parameter parameter
static void Method(out Suit parameter){ parameter = Suit.Hearts;}
static void Main(){ Suit arg; //Console.Write(arg); Method(out arg); Console.Write(arg);}
Hearts
© { JSL }6666
in P
aram
eter
s?in
Par
amet
ers?
readonlyreadonly, , constconst and and inin, are all C# keywords, are all C# keywords they cannot be applied to parametersthey cannot be applied to parameters refref / / outout parameters parameters alwaysalways grant write access grant write access for value types simply pass by copyfor value types simply pass by copy
argument parameter
@
@
optional
required
Copy
ref
outClubs
initialize
Clubs
Clubs Clubs
© { JSL }6767
Par
amet
er N
ote
s P
aram
eter
No
tes
sdsdclass Notes{
... Good( int copy) ...
... Error(ref int alias) ...
... Error(out int alias) ...
... Error(float /*noname*/) ...
... Error(double d = 0.0) ...
... Error(const ref Wibble w) ...
... Error(void) ...
}
struct BadPair{ ref int x; out int y;}
ref and out cannotbe used as fieldmodifiers (or returntype modifiers)
ref, out modifieris part of signature
must name parameter
no default arguments(overload instead)
no readonly parameters
no void parameter
can't overload basedsoley on ref out
© { JSL }6868
Mo
re N
ote
sM
ore
No
tes
class Notes{ int Error() { ... } double Error() { ... }}
return type is not part of signature
int Global() { ... }
no trailing semi-colon
no global functions
class Notes{ int Error(); void AlsoError() {};}
definition must be inline
© { JSL }6969
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
Co
ntr
ol F
low
Co
ntr
ol F
low
© { JSL }7070
Blo
cks
Blo
cks
a block and its parent block a block and its parent block cannot have a variable with the same namecannot have a variable with the same name
sibling blocks sibling blocks can have variables with the same namecan have variables with the same name
int m;{ int m; ...}
compiletime error
OK
{ int m; ...}{ int m; ...}
© { JSL }7171
ifif no built-in conversions to/from boolno built-in conversions to/from bool
System.ConvertSystem.Convert .ToBoolean(int i) exists though.ToBoolean(int i) exists though
definite assignment consequencesdefinite assignment consequences just like in Javajust like in Java
if (number % 2 == 0) parity = "odd";else parity = "even";
if ( boolean-expression ) embedded-statementelse embedded-statement
if ( boolean-expression ) embedded-statementelse embedded-statement
if (number % 2 == 0) string parity = "even";...
OK
compiletime error
string parity = number % 2 == 0 ? "odd" : "even";
ternary operator
© { JSL }7272
swit
chsw
itch
usual syntaxusual syntax switchswitch on integral types on integral types casecase labels must be compile time constants labels must be compile time constants etcetc
switch (trumps){case Suit.Clubs: ... break;case Suit.Hearts: ... break;case Suit.Diamonds: ... break;case Suit.Spades: ... break;default: ... break;}
© { JSL }7373
case
No
tes
case
No
tes
unusual syntaxunusual syntax you you cancan switchswitch on a on a stringstring fall through is illegal, even on fall through is illegal, even on defaultdefault clause clause you can you can gotogoto a a casecase//defaultdefault label label !!
void Func(string option){ switch (option) { case "label": goto case "jump": case "jump": goto default; case "quit": return; case "spin": for(;;){ } case "unwind": throw new Exception(); default: break; }}
© { JSL }7474
wh
ile/d
ow
hile
/do
standard Java,C++ like syntaxstandard Java,C++ like syntax
int m = 0;while (m != 10){ Console.Write("{0} ", m); m++;}
int m = 0;do{ Console.Write("{0} ", m); m++;}while (m != 10)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
© { JSL }7575
for
for
forfor statement statement declared variables are scoped to declared variables are scoped to forfor statement statement
for (int m = 0; m != 10; m++){ Console.Write("{0} ", m);}for (int m = 0; m != 10; m++){ Console.Write("{0} ", m);}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
© { JSL }7676
fore
ach
fore
ach
from shell, VB, PERL, etcfrom shell, VB, PERL, etc works on any collection, including [ ] arraysworks on any collection, including [ ] arrays
using System.Collections;
class Example{ static void Main() { ArrayList numbers = new ArrayList(); ... // fill numbers with 0 through 9 ... foreach (int number in numbers) { Console.Write("{0} ", number); } }}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 ArrayList C++ vector<>
© { JSL }7777
fore
ach
No
tes
fore
ach
No
tes
foreach foreach (( typetype identifieridentifier in in expressionexpression )) type and identifier declare an iteration variabletype and identifier declare an iteration variable implicitly implicitly readonlyreadonly, can't be , can't be refref or or outout parameter parameter expression must be eitherexpression must be either
an IEnumerable collection, oran IEnumerable collection, or a "collection type"a "collection type"
conversion must exist, could throwconversion must exist, could throw
ArrayList numbers = new ArrayList();...// fill numbers with 0 through 9...IEnumerator ie = numbers.GetEnumerator();while (ie.MoveNext()){ int number = (int)ie.Current; Console.WriteLine(number);}
© { JSL }7878
con
tin
ue/
bre
akco
nti
nu
e/b
reak
no labelled no labelled breakbreak statement statement
int m = 0;for (;;){ Console.Write("{0} ", m); m++; if (m != 10) continue; else break;}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
© { JSL }7979
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
stru
ctst
ruct
© { JSL }8080
stru
ct D
ecla
rati
on
stru
ct D
ecla
rati
on
a user-a user- defined defined valuevalue-- typetype
struct Pair{ public int X, Y;};
optional semi-colon
by convention publicnames start with anuppercase letter(PascalCase)
struct Pair{ private int x, y;}
...and private names start with alowercase letter(camelCase)
struct Pair{ int x, y;}
default accessis private
© { JSL }8181
stru
ct C
reat
ion
stru
ct C
reat
ion
a a structstruct local variable lives on the stack local variable lives on the stack is not definitely assigned, just like is not definitely assigned, just like intint can can alwaysalways be initialised with a default c'tor call be initialised with a default c'tor call
p.X
stack
?
?p.Y
p.X 0
0p.Y
...static void Main(){ Pair p; Console.Write(p.X); ...}
...static void Main(){ Pair p = new Pair(); Console.Write(p.X); ...}
compiletime error
© { JSL }8282
stru
ct U
se
stru
ct U
se
usual dot operator to access fieldusual dot operator to access field field must be assigned before its value is usedfield must be assigned before its value is used default c'tor default initialises fields zero/default c'tor default initialises fields zero/falsefalse//nullnull
...static void Main(){ Pair p; p.X = 0; Console.Write(p.X);}
...static void Main(){ Pair p = new Pair(); Console.Write(p.X);}
p.X
stack
0
?p.Y
p.X 0
0p.Y
© { JSL }8383
stru
ct C
on
stru
cto
rst
ruct
Co
nst
ruct
or
unusual rulesunusual rules compiler declares default c'torcompiler declares default c'tor you you cannotcannot declare the default c'tor declare the default c'tor default c'tor zero-initialises all instance fieldsdefault c'tor zero-initialises all instance fields
struct Pair{}
compile time error
struct Pair{ public Pair(int x, int y) {...} }
compiler declares a default c'tor
struct Pair{ public Pair() { ... }}
compiler declared default c'tor still exists
© { JSL }8484
: th
is(.
..):
this
(...)
a c'a c' tor can call a sibling c'tor can call a sibling c' tortor syntax is similar to C++syntax is similar to C++ no general member-init-list syntax thoughno general member-init-list syntax though
struct ColoredPoint{ public ColoredPoint(int x, int y) : this(x, y, Colour.Red) { } public ColoredPoint(int x, int y, Colour c) { ... } ... private int x, y; private Colour c;}
© { JSL }8585
inst
ance
Fie
lds
inst
ance
Fie
lds
instance fields...instance fields... are default initialised in compilers default c'torare default initialised in compilers default c'tor must be explicitly initialised in users c'tormust be explicitly initialised in users c'tor
struct BadPair{ public BadPair(int x, int y) { this.x = x; } private int x; private int y = 0;}
compile time error: one instance field not intialised
okay: all instance fields explicitly initialised
struct GoodPair{ public GoodPair(int x, int y) { this.x = x; this.y = y; } private int x, y;}
compile time error: instance field cannot be intialised here
© { JSL }8686
read
on
ly F
ield
sre
ado
nly
Fie
lds
readonlyreadonly instance fields... instance fields... are instance fields that cannot be assigned toare instance fields that cannot be assigned to
compile time errors
struct Pair{ public Pair(int x, int y) { this.x = x; this.y = y; } public void Reset() { x = 0; y = 0; } private readonly int x, y;}
this declares Pair as an immutable value
© { JSL }8787
con
st F
ield
sco
nst
Fie
lds
constconst fields are implicitly fields are implicitly staticstatic only simple types, only simple types, enumenums, & s, & stringstring can be can be constconst constconst fields require a variable initialiser fields require a variable initialiser must be initialized to compile time constant valuemust be initialized to compile time constant value
struct Pair{ private const int x = 0, y = 0;}
struct BadFields{... BadFields(...) { question = 9 * 6; }... static const int answer = 42;... const int question;... const Pair origin = new Pair();}
OK
compile time errors
this declares Pair with no instance fields
...implicitly static
...can't initialize here
...not initialized...Pair not simple type
© { JSL }8888
stat
ic F
ield
sst
atic
Fie
lds
to declare to declare staticstatic fields of other types fields of other types useuse static static keyword keyword!! staticstatic fields are default initialised fields are default initialised staticstatic fields can use variable initialisers fields can use variable initialisers access is via typename onlyaccess is via typename only
struct Pair{... static Pair origin;... static Pair topLeft = new Pair(10,20);... static AnyClass field;... static string both = "Arthur";}
Pair p = new Pair();...F(p.Origin); F(Pair.Origin);
compile time error
okay
© { JSL }8989
Lo
cal V
aria
ble
sL
oca
l Var
iab
les
local variables can be declared local variables can be declared constconst but not but not static, static, and not and not readonlyreadonly and and constconst is only for is only for simplesimple types types must be initialized to compile time constant valuemust be initialized to compile time constant value
struct GoodExample{... void Func() { const int answer = 42; const Suit trumps = Suit.Club; }}
OK
struct BadExample{... void Func() { const int lv = F(); static Pair origin = ...; readonly Pair p = ...; }}
compiletimeerrors
© { JSL }9090
stat
ic C
on
stru
cto
rst
atic
Co
nst
ruct
or
a a staticstatic c'tor initialises the type c'tor initialises the type can initialize can initialize staticstatic fields but not fields but not constconst fields fields called by VES when the type is loadedcalled by VES when the type is loaded cannot be called, no access modifier allowedcannot be called, no access modifier allowed
struct GoodExample{ static GoodExample() { origin = new Pair(0,0); }...static readonly Pair origin;}
OK
struct BadExample{ public static BadExample() { x = 42; }...const int x;}
compile time errors
© { JSL }9191
Co
py
Co
nst
ruct
or?
Co
py
Co
nst
ruct
or?
you can declare a "copy constructor"you can declare a "copy constructor" it is it is notnot called for value parameters/returns called for value parameters/returns a copy is a copy is alwaysalways a plain bitwise copy a plain bitwise copy
struct Pair{... Pair(Pair other) { ... } ...}
struct Pair{... Pair Func() ...... void Func(Pair copy) { Pair p = new Pair(copy); }}
calling this doesnot result ininfinite recursion
these do not call the copy c'tor
only this does
© { JSL }9292
Co
py
Ass
ign
men
t?C
op
y A
ssig
nm
ent?
you cannot overload simple assignmentyou cannot overload simple assignment a copy is a copy is alwaysalways a plain bitwise copy a plain bitwise copy
struct Pair{ public static Pair operator=(Pair lhs, Pair rhs) { ... } ...}
struct Pair{... void Func(Pair lhs, Pair rhs) { lhs = rhs; ... }}
you can't do this.compile time error
simple assignment
© { JSL }9393
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
Op
erat
ors
Op
erat
ors
© { JSL }9494
Ove
rlo
adin
gO
verl
oad
ing
you can you can overload most operatorsoverload most operators
you can'tyou can't create new operatorscreate new operators change the multiplicity or precedencechange the multiplicity or precedence change the associativity or order of evaluationchange the associativity or order of evaluation change the meaning of built in operatorschange the meaning of built in operators
unary + - ! ~ ++ -- true false
binary + - * / % & | ^ << >>
== != > < >= <=
© { JSL }9595
op
erat
or
Syn
tax
op
erat
or
Syn
tax
operators are always defined asoperators are always defined as publicpublic staticstatic methods (never methods (never virtualvirtual)) copy parameters only (not copy parameters only (not refref--outout ) ) one+ parameter must be of containing typeone+ parameter must be of containing type
struct Meter{ ... public static Meter operator + (Meter lhs, Meter rhs) { return new Meter(lhs.value + rhs.value); } ...}
don't forget the newvoid Func(Meter lhs, Meter rhs)
{ Stuff(lhs + rhs);}
© { JSL }9696
Ass
ign
men
tA
ssig
nm
ent
you can't overload assignment, but this...you can't overload assignment, but this...
X op= Y
X = X op Y
is processed as this...
except that X is evaluated only once
public static Meter operator + (Meter lhs, Meter rhs){ ...}
void Func(Meter lhs, Meter rhs){ lhs += rhs; ...}
© { JSL }9797
++
--
++
-- you can overload ++ and --you can overload ++ and --
a a singlesingle operator supports prefix operator supports prefix andand postfix postfix prefix returns the result of the callprefix returns the result of the call postfix returns the operand before the callpostfix returns the operand before the call
struct Meter{ public static Meter operator ++ (Meter arg) { arg.value++; return arg; } ...}
Meter distance;...postfix = distance++;
Meter distance;...prefix = ++distance;
© { JSL }9898
op
erat
or
Fam
ilies
op
erat
or
Fam
ilies
some operators have natural partnerssome operators have natural partners you can't have one without the otheryou can't have one without the other
struct Meter{ public static bool operator == (Meter lhs, Meter rhs) ... public static bool operator != (Meter lhs, Meter rhs) ...}
true false
== !=
< >
<= >=
© { JSL }9999
op
erat
or
tru
e/fa
lse
op
erat
or
tru
e/fa
lse
designed for tri-state boolean typesdesigned for tri-state boolean types eg SQL types: eg SQL types: truetrue, , falsefalse, Null, Null
also have the effect ofalso have the effect of creating an implicit conversion to creating an implicit conversion to boolbool can overload && || in combination with & |can overload && || in combination with & |
struct DBaseBool{ public static bool operator false (DBbaseBool arg) ... public static bool operator true (DBbaseBool arg) ...}
© { JSL }100100C
on
vers
ion
sC
on
vers
ion
s must be must be public public andand static static must be must be implicit implicit oror explicit explicit
implicitimplicit : compiler can call, should never throw : compiler can call, should never throw explicit : explicit : compiler can't call, cast required, may compiler can't call, cast required, may
throwthrow
struct DBaseBool{ public static implicit operator DBbaseBool (bool from) ... public static explicit operator bool (DBbaseBool from) ...}
© { JSL }101101E
xam
ple
Exa
mp
le "readonly" local variable"readonly" local variable
struct ConstInt{ public ConstInt(int value) { this.value = value; }
public static implicit operator int(ConstInt from) { return from .value; } private readonly int value;}
class Example{ ... public void Method() { ConstInt local = new ConstInt(42); local++; // compile time error ... }}
© { JSL }102102C
on
vers
ion
No
tes
Co
nve
rsio
n N
ote
s implicitimplicit conversion resolution conversion resolution
optional standard optional standard implicitimplicit conversion conversion user defined user defined implicitimplicit conversion conversion optional standard optional standard implicitimplicit conversion conversion
explicitexplicit conversion resolution conversion resolution optional standard optional standard explicitexplicit conversion conversion user defined user defined implicitimplicit or or explicitexplicit conversion conversion optional standard optional standard explicitexplicit conversion conversion
a single argument constructor is never a converting constructor
you cannot create conversions to interfaces
© { JSL }103103
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
Ind
exer
sIn
dex
ers
© { JSL }104104[
][
] indexers provide [ ] like syntax of useindexers provide [ ] like syntax of use
always an instance member, can be always an instance member, can be virtualvirtual no no refref--out out parametersparameters can be overloadedcan be overloaded
class DoubleArray{ ... public double this [int index] { ... } ...} an indexer
is not an operator
DoubleArray marks;...marks[2] = 34.29;...if (marks[0] > 42.0) ...
no parentheses
this is a keyword
© { JSL }105105g
et a
nd
set
get
an
d s
et indexers can only contain accessorsindexers can only contain accessors
getget { accessor } for read context { accessor } for read context setset { accessor } for write context { accessor } for write context
class DoubleArray{ ... public double this [int index] { get { return ...; }
set { ... = value; } } ...}
marks[2] = 34.29;
if (marks[0] > 50.0) ...
© { JSL }106106g
et o
r se
tg
et o
r se
t an indexer with no an indexer with no setset accessor accessor
is a read-only indexeris a read-only indexer
and indexer with no and indexer with no getget accessor accessor is a write-only indexeris a write-only indexer
class Hand{ ... public Card this [int index] { get { return ... } }}
void Cheat(Hand current){ Card ace = MakeAce(Suit.Spades); ... current[0] = ace; }
compile time error
© { JSL }107107In
dex
er N
ote
sIn
dex
er N
ote
s indexers compared to arraysindexers compared to arrays
indexers can use multiple parametersindexers can use multiple parameters indexers can use non integer indexesindexers can use non integer indexes indexers can be overloadedindexers can be overloaded indexers can be declared in an indexers can be declared in an interfaceinterface
interface IMatrix{ ... double this [int row, int col] { get; set; } ...}
© { JSL }108108
C# ProgrammingC# Programming
Fundamentals
Objects
Relationships
Systems
Pro
per
ties
Pro
per
ties
© { JSL }109109g
et a
nd
set
Ag
ain
get
an
d s
et A
gai
n an object oriented smart fieldan object oriented smart field
getget and and setset accessors accessors instance property can be instance property can be virtualvirtual
struct Pair{ ... public int X { get { return x; } set { x = value; } } private int x, y;}
Pair p; ...p.X = 0;...Console.Write(p.X);
note no ( ) hereand capital X
© { JSL }110110st
atic
Pro
per
ties
stat
ic P
rop
erti
es properties can be properties can be staticstatic
unlike indexersunlike indexers
class Console{ ... public static readonly TextWriter Out { get { ... } } private static TextWriter out = null;}
struct DateTime{ ... public static DateTime Today { get { ... } } ...}
possiblelazycreation
© { JSL }111111P
rop
erty
No
tes
Pro
per
ty N
ote
s propertiesproperties
are not lvalues, can't be are not lvalues, can't be refref--outout args args can't be can't be voidvoid can't take arbitrary parameterscan't take arbitrary parameters can be can be virtualvirtual instance properties can go in an instance properties can go in an interfaceinterface
interface IAccount{ ... decimal Balance { get; } ...}
© { JSL }112112S
um
mar
yS
um
mar
y .NET, IL, CLS, CLR, VES.NET, IL, CLS, CLR, VES stack values – stack values – enumenum, , structstruct (eg (eg int int )) control flow – control flow – switchswitch, , foreachforeach functionsfunctions
ref-outref-out parameters parameters no global functions, by default no global functions, by default notnot virtualvirtual constconst – but only for simple types and – but only for simple types and stringstring
operatorsoperators always always public,public, always always staticstatic compound assignment, ++, familiescompound assignment, ++, families conversions – conversions – implicitimplicit and and explicitexplicit
getget and and setset { accessors } { accessors } instance indexers [ ] [ , ] instance indexers [ ] [ , ] instance and instance and staticstatic properties properties