Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
© { JSL }
1
C#inDetail
Jon Jagger
Software Trainer, Designer, Consultant
www.jaggersoft.com
jon@jaggersoft.com
{ JSL }
Par...
© { JSL }
2
BlatantAdvert
 an interactive, friendly, expert instructor
 Jon has worked for Microsoft using C#
 lots of ...
© { JSL }
3
Agenda  overview
 built-in value types
 enums
 parameters
 control flow
 structs
 constructors
 fields...
© { JSL }
4
C# Programming
Fundamentals
Objects
Relationships
Systems
Overview
© { JSL }
5
C#Features static typing
runtime polymorphism
operator overloading
exceptions
multiple public realization
non ...
© { JSL }
6
HelloUniverse Hiker.cs
using System;
public class Hiker
{
public static void Main()
{
int result;
result = 9 *...
© { JSL }
7
MSIL
C:Sharp>ildasm Hiker.exe
© { JSL }
8
VES  intermediate language, IL
 loading managed code including resolving names
 conversion of IL into nativ...
© { JSL }
9
FortyTwo  C# programs are constructed from tokens
Hiker.cs
/*
*/
using System;
public class Hiker
{
public st...
© { JSL }
10
Tokens  five kinds of tokens in C# programs
token examples
identifiers Hiker Main result
keywords public cla...
© { JSL }
11
Pre-processing  C# has a sensibly limited "preprocessor"
 no #include, no #pragma
 #define, but no macros
...
© { JSL }
12
Identifiers  rules
 made of letters and digits
 must start with a letter
 underscore is a letter
 case s...
© { JSL }
13
Keywords  some identifiers have a fixed meaning
using System;
public class Hiker
{
public static void Main()...
© { JSL }
14
KeywordTable  76 keywords (+ 5 ish)
abstract as base bool break
byte case catch char checked
class const con...
© { JSL }
15
Literals  some tokens represent fixed values
type literal
bool true false
double 3.1415
char 'X'
int 9 6 13 ...
© { JSL }
16
Operators  some tokens represent fixed actions
symbol category
+ - * / % arithmetic
&& || ! logical
< <= > >...
© { JSL }
17
Punctuators  some tokens group or separate
 { and } form scoped blocks
 semi-colons mark the end of a simp...
© { JSL }
18
Declarations  declarations introduce variables into a scope
 a variable has an identifier and a type
 a va...
© { JSL }
19
Expressions  expressions compute things!
 an expression yields a value
 an expression must also have a sid...
© { JSL }
20
TwoTypes  value types
 variables contain their own data directly
 local variables always live on the stack...
© { JSL }
21
C# Programming
Fundamentals
Objects
Relationships
Systems
bool
© { JSL }
22
bool  bool is a keyword
 an alias for System.Boolean
 only values are true and false
bool love = true;
boo...
© { JSL }
23
System.Boolean
namespace System
{
public struct Boolean ...
{
// static fields
public static readonly string ...
© { JSL }
24
boolOperators
int tens = 9 * 6 / 13;
int units = 9 * 6 % 13;
bool isFour = tens == 4;
bool isTwo = units == 2...
© { JSL }
25
boolConversios  no implicit conversions to bool
 ever
 none
 nada
 zip
 under any circumstances whatsoe...
© { JSL }
26
C# Programming
Fundamentals
Objects
Relationships
Systems
byteshortintlong
© { JSL }
27
IntegerTypes
type bits System.
short 16 Int16
int 32 Int32
long 64 Int64
sbyte 8* SByte
ushort 16 Uint16
uint...
© { JSL }
28
System.Int32 namespace System
{
public struct Int32 ...
{
// static fields
public const int MaxValue;
public ...
© { JSL }
29
IntegerLiterals
decimal-integer-literal:
decimal-digits integer-type-suffixopt
decimal-digits:
decimal-digit
...
© { JSL }
30
IntegerOperators
assignment =
in-equality == !=
relational < > <= >=
arithmetic + - * / %
bitwise | & ^ ~
shi...
© { JSL }
31
PrimaryOperators grouping (x)
access x.y
method call f(x)
indexing a[x]
post-increment x++
post-decrement x--...
© { JSL }
32
Precedence primary see previous slide
unary + - ! ~ ++x –-x (T)x
multiplicative * / %
additive + -
shift << >...
© { JSL }
33
Associativity  rule 1
 except for the assignment operators all binary
operators are left-associative
 rule...
© { JSL }
34
EvaluationOrder  operands are evaluated strictly left to right
 same as in Java, unspecified in C++
int m =...
© { JSL }
35
IntegerOverflow  DivideByZeroException, OverflowException
 un/checked expressions
 un/checked { statements...
© { JSL }
36
IntegerMSIL  integer MSIL instructions come in two forms
 one checks for overflow ( eg mul.ovf )
 one does...
© { JSL }
37
IntegerShifting  never throw exceptions
 (u)int shift  count & 0x1F
 (u)long shift  count & 0x3F
int ope...
© { JSL }
38
IntegerConversions  implicit, widening conversions
 never lose information, never throw exception
 explici...
© { JSL }
39
sbyte
short
int
long
sbyte
short
int
long
byte
ushort
uint
ulong
byte
ushort
uint
ulong
signed unsigned
signe...
© { JSL }
40
C# Programming
Fundamentals
Objects
Relationships
Systems
floatdouble
© { JSL }
41
F.P.Types
type
bits
System.
float
32
Single
double
64
Double
CLS
sig. figs 157
yes yes
MSIL float32 float64
±...
© { JSL }
42
System.Double
namespace System
{
public struct Double ...
{
// static fields
public const double Epsilon;
pub...
© { JSL }
43
F.P.Literals real-literal:
digits . digits exponentopt suffixopt
. digits exponentopt suffixopt
digits expone...
© { JSL }
44
F.P.Operators  mostly the same as the integers
 modulus % is permitted (it's not in C++)
 shift operators ...
© { JSL }
45
F.P.Conversions  double  float
 explicit conversion
 never throws
 integer  floating point
 implicit c...
© { JSL }
46
C# Programming
Fundamentals
Objects
Relationships
Systems
decimal
© { JSL }
47
decimalType 
type
bits
System.
decimal
128
Decimal
CLS
sig. figs 28
yes
± 7.9x1028range
suffix M m
float
32
...
© { JSL }
48
System.Decimal namespace System
{
public struct Decimal ...
{
// static fields
public static readonly decimal...
© { JSL }
49
moreConversions  float / double  decimal
 explicit conversion (FP have greater range)
 always checked, ma...
© { JSL }
50
C# Programming
Fundamentals
Objects
Relationships
Systems
char
© { JSL }
51
charType
type
bits
System.
char
16
Char
CLS yes
0x0000
0xFFFF
min
max
Unicode 3.0
You idiot, that's a chair
© { JSL }
52
System.Char
namespace System
{
public struct Char ...
{
// static fields
public const char MaxValue;
public c...
© { JSL }
53
charLiterals character-literal:
' character '
character:
single-character
simple-escape-character
hex-escape-...
© { JSL }
54
charConversions  char is classified as an integral type
 you can do char arithmetic
 implicit conversion f...
© { JSL }
55
C# Programming
Fundamentals
Objects
Relationships
Systems
enum
© { JSL }
56
enumDeclaration  a user-declared value-type
enum Suit
{
Clubs, Diamonds, Hearts, Spades
};
class Example
{
s...
© { JSL }
57
enumNotes
enum Suit : int
{
Clubs,
Diamonds,
Hearts = 42,
Spades,
}
the underlying integer type
can be any of...
© { JSL }
58
enumUse  enums implicitly derive from System.Enum
Suit trumps = Suit.Club;
string[] names = System.Enum.GetN...
© { JSL }
59
enumOperators  enum variables can mostly be used as ints
assignment =
in-equality == !=
relational < > <= >=...
© { JSL }
60
enumConversions  implicit conversion
 literal 0 to any enum type
 explicit conversions
 from enum to enum...
© { JSL }
61
Terminology  two kinds of value type
 enum types
 struct types
 two kinds of struct types
 user-defined ...
© { JSL }
62
C# Programming
Fundamentals
Objects
Relationships
Systems
Parameters
© { JSL }
63
CopyParameters  a plain parameter is a copy of the argument
 no frills bitwise copy
 the argument must be ...
© { JSL }
64
refParameters  a ref parameter is an alias for the argument
 no copy takes place
 argument must be definit...
© { JSL }
65
outParameters  an out parameter is an alias for the argument
 no copy takes places
 argument need not be d...
© { JSL }
66
inParameters?  readonly, const and in, are all C# keywords
 they cannot be applied to parameters
 ref / ou...
© { JSL }
67
ParameterNotes  sdclass Notes
{
... Good( int copy) ...
... Error(ref int alias) ...
... Error(out int alias...
© { JSL }
68
MoreNotes
class Notes
{
int Error() { ... }
double Error() { ... }
}
return type is not
part of signature
int...
© { JSL }
69
C# Programming
Fundamentals
Objects
Relationships
Systems
ControlFlow
© { JSL }
70
Blocks  a block and its parent block
 cannot have a variable with the same name
 sibling blocks
 can have...
© { JSL }
71
if  no built-in conversions to/from bool
 System.Convert.ToBoolean(int i) exists though
 definite assignme...
© { JSL }
72
switch  usual syntax
 switch on integral types
 case labels must be compile time constants
 etc
switch (t...
© { JSL }
73
caseNotes  unusual syntax
 you can switch on a string
 fall through is illegal, even on default clause
 y...
© { JSL }
74
while/do  standard Java,C++ like syntax
int m = 0;
while (m != 10)
{
Console.Write("{0} ", m);
m++;
}
int m ...
© { JSL }
75
for  for statement
 declared variables are scoped to for statement
for (int m = 0; m != 10; m++)
{
Console....
© { JSL }
76
foreach  from shell, VB, PERL, etc
 works on any collection, including [ ] arrays
using System.Collections;...
© { JSL }
77
foreachNotes  foreach ( type identifier in expression )
 type and identifier declare an iteration variable
...
© { JSL }
78
continue/break  no labelled break statement
int m = 0;
for (;;)
{
Console.Write("{0} ", m);
m++;
if (m != 10...
© { JSL }
79
C# Programming
Fundamentals
Objects
Relationships
Systems
struct
© { JSL }
80
structDeclaration  a user-defined value-type
struct Pair
{
public int X, Y;
};
optional semi-colon
by conven...
© { JSL }
81
structCreation  a struct local variable lives on the stack
 is not definitely assigned, just like int
 can...
© { JSL }
82
structUse  usual dot operator to access field
 field must be assigned before its value is used
 default c'...
© { JSL }
83
structConstructor  unusual rules
 compiler declares default c'tor
 you cannot declare the default c'tor
 ...
© { JSL }
84
:this(...)  a c'tor can call a sibling c'tor
 syntax is similar to C++
 no general member-init-list syntax...
© { JSL }
85
instanceFields  instance fields...
 are default initialised in compilers default c'tor
 must be explicitly...
© { JSL }
86
readonlyFields  readonly instance fields...
 are instance fields that cannot be assigned to
compile time er...
© { JSL }
87
constFields  const fields are implicitly static
 only simple types, enums, & string can be const
 const fi...
© { JSL }
88
staticFields  to declare static fields of other types
 use static keyword!
 static fields are default init...
© { JSL }
89
LocalVariables  local variables can be declared const
 but not static, and not readonly
 and const is only...
© { JSL }
90
staticConstructor  a static c'tor initialises the type
 can initialize static fields but not const fields
...
© { JSL }
91
CopyConstructor?  you can declare a "copy constructor"
 it is not called for value parameters/returns
 a c...
© { JSL }
92
CopyAssignment?  you cannot overload simple assignment
 a copy is always a plain bitwise copy
struct Pair
{...
© { JSL }
93
C# Programming
Fundamentals
Objects
Relationships
Systems
Operators
© { JSL }
94
Overloading  you can
 overload most operators
 you can't
 create new operators
 change the multiplicity ...
© { JSL }
95
operatorSyntax  operators are always defined as
 public static methods (never virtual)
 copy parameters on...
© { JSL }
96
Assignment  you can't overload assignment, but this...
X op= Y
X = X op Y
is processed as this...
except tha...
© { JSL }
97
++--  you can overload ++ and --
 a single operator supports prefix and postfix
 prefix returns the result...
© { JSL }
98
operatorFamilies  some operators have natural partners
 you can't have one without the other
struct Meter
{...
© { JSL }
99
operatortrue/false  designed for tri-state boolean types
 eg SQL types: true, false, Null
 also have the e...
© { JSL }
100
Conversions  must be public and static
 must be implicit or explicit
 implicit : compiler can call, shoul...
© { JSL }
101
Example  "readonly" local variable
struct ConstInt
{
public ConstInt(int value)
{
this.value = value;
}
pub...
© { JSL }
102
ConversionNotes  implicit conversion resolution
 optional standard implicit conversion
 user defined impl...
© { JSL }
103
C# Programming
Fundamentals
Objects
Relationships
Systems
Indexers
© { JSL }
104
[]  indexers provide [ ] like syntax of use
 always an instance member, can be virtual
 no ref-out parame...
© { JSL }
105
getandset  indexers can only contain accessors
 get { accessor } for read context
 set { accessor } for w...
© { JSL }
106
getorset  an indexer with no set accessor
 is a read-only indexer
 and indexer with no get accessor
 is ...
© { JSL }
107
IndexerNotes  indexers compared to arrays
 indexers can use multiple parameters
 indexers can use non int...
© { JSL }
108
C# Programming
Fundamentals
Objects
Relationships
Systems
Properties
© { JSL }
109
getandsetAgain  an object oriented smart field
 get and set accessors
 instance property can be virtual
s...
© { JSL }
110
staticProperties  properties can be static
 unlike indexers
class Console
{
...
public static readonly Tex...
© { JSL }
111
PropertyNotes  properties
 are not lvalues, can't be ref-out args
 can't be void
 can't take arbitrary p...
© { JSL }
112
Summary  .NET, IL, CLS, CLR, VES
 stack values – enum, struct (eg int )
 control flow – switch, foreach
...
Upcoming SlideShare
Loading in …5
×

Csharp In Detail Part1

4,659 views

Published on

Published in: Business, Technology
  • Be the first to comment

Csharp In Detail Part1

  1. 1. © { JSL } 1 C#inDetail Jon Jagger Software Trainer, Designer, Consultant www.jaggersoft.com jon@jaggersoft.com { JSL } Part 1
  2. 2. © { JSL } 2 BlatantAdvert  an interactive, friendly, expert instructor  Jon has worked for Microsoft using C#  lots of great exercises  to make sure you understand  even more slides  with detail, explanations, and rationales  full slide notes  include careful comparisons with C++ and Java C# in Detail is also available as an instructor led course
  3. 3. © { JSL } 3 Agenda  overview  built-in value types  enums  parameters  control flow  structs  constructors  fields  operators  indexers  properties
  4. 4. © { JSL } 4 C# Programming Fundamentals Objects Relationships Systems Overview
  5. 5. © { JSL } 5 C#Features static typing runtime polymorphism operator overloading exceptions multiple public realization non deterministic finalization multi threading compile time polymorphism ? value types garbage collection single public inheritance unified type system Object super base class virtual execution system reflection reference types C#, C++ and Java C# and JavaC# and C++ C#
  6. 6. © { JSL } 6 HelloUniverse 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.exe 42// single-line comment
  7. 7. © { JSL } 7 MSIL C:Sharp>ildasm Hiker.exe
  8. 8. © { JSL } 8 VES  intermediate language, IL  loading managed code including resolving names  conversion of IL into native code  verification of the type safety of the IL  verification of integrity of the metadata  garbage collection services  initiation, propagation, and intercepting exceptions  profiling and debugging services  management of threads, contexts, and remoting
  9. 9. © { JSL } 9 FortyTwo  C# 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)
  10. 10. © { JSL } 10 Tokens  five kinds of tokens in C# programs token examples identifiers Hiker Main result keywords public class int literals 9 6 13 operators + - * / % = punctuators ; { } ,
  11. 11. © { JSL } 11 Pre-processing  C# has a sensibly limited "preprocessor"  no #include, no #pragma  #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
  12. 12. © { JSL } 12 Identifiers  rules  made of letters and digits  must start with a letter  underscore is a letter  case sensitive  recommendations  don't use underscores  don't abbreviate  don't use hungarian  follow style guidelines different Different answer42 42Answer    rare_style privateStyle PublicStyle msg message !CLS camel Case Pascal Case
  13. 13. © { JSL } 13 Keywords  some 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 */
  14. 14. © { JSL } 14 KeywordTable  76 keywords (+ 5 ish) abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void while get set value add remove These are sometimes reserved Any keyword can be used as an identifier if preceeded by @
  15. 15. © { JSL } 15 Literals  some 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 sequences of characters object nullnothing
  16. 16. © { JSL } 16 Operators  some tokens represent fixed actions symbol category + - * / % arithmetic && || ! logical < <= > >= relational == != equality = assignment & | ^ ~ << >> bitwise
  17. 17. © { JSL } 17 Punctuators  some tokens group or separate  { and } form scoped blocks  semi-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); } }
  18. 18. © { JSL } 18 Declarations  declarations introduce variables into a scope  a variable has an identifier and a type  a variable's type can never 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, another ;
  19. 19. © { JSL } 19 Expressions  expressions compute things!  an expression yields a value  an expression must also have a side-effect 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); } }
  20. 20. © { JSL } 20 TwoTypes  value types  variables contain their own data directly  local variables always live on the stack  reference types  variables refer to their data indirectly  local variables refer to objects on the heap object valueenum class interface [ ]array delegate struct value object object object @ @ @ @
  21. 21. © { JSL } 21 C# Programming Fundamentals Objects Relationships Systems bool
  22. 22. © { JSL } 22 bool  bool is a keyword  an alias for System.Boolean  only values are true and false 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;    
  23. 23. © { JSL } 23 System.Boolean 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());
  24. 24. © { JSL } 24 boolOperators 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
  25. 25. © { JSL } 25 boolConversios  no implicit conversions to bool  ever  none  nada  zip  under any circumstances whatsoever
  26. 26. © { JSL } 26 C# Programming Fundamentals Objects Relationships Systems byteshortintlong
  27. 27. © { JSL } 27 IntegerTypes 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
  28. 28. © { JSL } 28 System.Int32 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);
  29. 29. © { JSL } 29 IntegerLiterals 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
  30. 30. © { JSL } 30 IntegerOperators assignment = in-equality == != relational < > <= >= arithmetic + - * / % bitwise | & ^ ~ shift << >> inc/dec ++ -- compound assignment
  31. 31. © { JSL } 31 PrimaryOperators 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
  32. 32. © { JSL } 32 Precedence primary see previous slide unary + - ! ~ ++x –-x (T)x multiplicative * / % additive + - shift << >> relational < > <= >= is as equality == != bitwise & ^ | boolean && || ?: assignment = *= /= %= += -= ...
  33. 33. © { JSL } 33 Associativity  rule 1  except for the assignment operators all binary operators are left-associative  rule 2  the assignment operators and the conditional operator (?:) are right-associative x + y + z  (x + y) + z x = y = z  x = (y = z)
  34. 34. © { JSL } 34 EvaluationOrder  operands are evaluated strictly left to right  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
  35. 35. © { JSL } 35 IntegerOverflow  DivideByZeroException, OverflowException  un/checked expressions  un/checked { statementsopt } 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+ *.cs csc /checked- *.cs
  36. 36. © { JSL } 36 IntegerMSIL  integer MSIL instructions come in two forms  one checks for overflow ( eg mul.ovf )  one doesn't check for overflow ( eg mul ) int a, b, c; ... .locals(int32 V0, int32 V1, int32 V2) int c = checked(a * b); ldloc.0 ldloc.1 mul.ovf stloc.2 int c = a * b; ldloc.0 ldloc.1 mul stloc.2 C# MSIL
  37. 37. © { JSL } 37 IntegerShifting  never throw exceptions  (u)int shift  count & 0x1F  (u)long shift  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
  38. 38. © { JSL } 38 IntegerConversions  implicit, widening conversions  never lose information, never throw exception  explicit narrowing conversions (casts)  may lose information, may throw exception short s; int m; .locals(int16 V0, int32 V1) ldloc.1 conv.ovf.i2 stloc.0 ldloc.1 conv.i2 stloc.0 s = checked((short)m); s = unchecked((short)m); s = (short)m; ? csc /checked+ csc /checked- C# IL
  39. 39. © { JSL } 39 sbyte short int long sbyte short int long byte ushort uint ulong byte ushort uint ulong signed unsigned signedunsigned ConversionTable • I I I E • I I E E • I E E E • E E E E E E E E E E E E E E E E E I I I E E I I E E E I E E E E • I I I E • I I E E • I E E E •
  40. 40. © { JSL } 40 C# Programming Fundamentals Objects Relationships Systems floatdouble
  41. 41. © { JSL } 41 F.P.Types 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
  42. 42. © { JSL } 42 System.Double 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(); ... } }
  43. 43. © { JSL } 43 F.P.Literals 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
  44. 44. © { JSL } 44 F.P.Operators  mostly the same as the integers  modulus % is permitted (it's not in C++)  shift operators are not permitted  FP arithmetic never throws exceptions  result too small  +/- zero  result too large  +/- infinity  invalid operation  NaN  either operand NaN  Nan
  45. 45. © { JSL } 45 F.P.Conversions  double  float  explicit conversion  never throws  integer  floating point  implicit conversion  never throws  may lose precision, never loses magnitude  floating point  integer  explicit conversion  may throw OverflowException (Beta-2 language specification says it won't)
  46. 46. © { JSL } 46 C# Programming Fundamentals Objects Relationships Systems decimal
  47. 47. © { JSL } 47 decimalType  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
  48. 48. © { JSL } 48 System.Decimal 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(); ... } }
  49. 49. © { JSL } 49 moreConversions  float / double  decimal  explicit conversion (FP have greater range)  always checked, may throw  decimal  float / double  explicit conversion (FP has less precision)  never throws, may lose precision  decimal  integral  explicit conversion (decimal has greater range)  always checked, may throw OverflowException  integral  decimal  implicit conversion  never throws, never loses information
  50. 50. © { JSL } 50 C# Programming Fundamentals Objects Relationships Systems char
  51. 51. © { JSL } 51 charType type bits System. char 16 Char CLS yes 0x0000 0xFFFF min max Unicode 3.0 You idiot, that's a chair
  52. 52. © { JSL } 52 System.Char 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(); ... } }
  53. 53. © { JSL } 53 charLiterals 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 octal escape
  54. 54. © { JSL } 54 charConversions  char is classified as an integral type  you can do char arithmetic  implicit conversion from char to  ushort, int, uint, long, ulong, float, double, decimal  explicit conversion from char to  sbyte, byte, short  no implicit conversions to char  even for sbyte, byte, and short
  55. 55. © { JSL } 55 C# Programming Fundamentals Objects Relationships Systems enum
  56. 56. © { JSL } 56 enumDeclaration  a user-declared value-type 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 compile time error okay
  57. 57. © { JSL } 57 enumNotes enum Suit : int { Clubs, Diamonds, Hearts = 42, Spades, } the underlying integer type can be any of the basic 8 integer types and defaults to int (not char) named constants can be initalized from constants; they default to the previous constant + 1 optional comma after last named constant
  58. 58. © { JSL } 58 enumUse  enums implicitly derive from System.Enum Suit trumps = Suit.Club; string[] names = System.Enum.GetNames(trumps.GetType()); ... Console.Write(names[0]); // Clubs Console.Write(trumps); // Clubs Console.Write("{0}", trumps); // Clubs Console.Write(trumps.ToString()); // Clubs Console.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(); } }
  59. 59. © { JSL } 59 enumOperators  enum variables can mostly be used as ints assignment = in-equality == != relational < > <= >= arithmetic + - * / % bitwise | & ^ ~ shift << >> inc/dec ++ -- yes yes yes yes no yes yes
  60. 60. © { JSL } 60 enumConversions  implicit conversion  literal 0 to any enum type  explicit conversions  from enum to enum via underlying type  from enum to numeric type (including char)  from numeric type (including char) to enum The set of values that an enum can take on is not limited by its enum members. Any value of the underlying type of the enum can be cast to the enum type, and is a distinct, valid value of that type. C# language spec (0.26)
  61. 61. © { JSL } 61 Terminology  two kinds of value type  enum types  struct types  two kinds of struct types  user-defined struct type  no literal syntax  simple struct types  integral types ( includes char )  floating point types ( includes decimal )  bool
  62. 62. © { JSL } 62 C# Programming Fundamentals Objects Relationships Systems Parameters
  63. 63. © { JSL } 63 CopyParameters  a plain parameter is a copy of the argument  no frills bitwise copy  the argument must be definitely assigned  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); } Clubs Clubs
  64. 64. © { JSL } 64 refParameters  a ref parameter is an alias for the argument  no copy takes place  argument must be definitely assigned  argument must be an "lvalue"  ref required on argument and 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); } Clubs Hearts
  65. 65. © { JSL } 65 outParameters  an out parameter is an alias for the argument  no copy takes places  argument need not be definitely assigned  parameter must be definitely assigned  argument must be an "lvalue"  out required on argument and 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
  66. 66. © { JSL } 66 inParameters?  readonly, const and in, are all C# keywords  they cannot be applied to parameters  ref / out parameters always grant write access  for value types simply pass by copy argument parameter @ @ optional required Copy ref outClubs initialize Clubs Clubs Clubs
  67. 67. © { JSL } 67 ParameterNotes  sdclass 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 cannot be used as field modifiers (or return type modifiers) ref, out modifier is part of signature must name parameter no default arguments (overload instead) no readonly parameters no void parameter can't overload based soley on ref out
  68. 68. © { JSL } 68 MoreNotes 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
  69. 69. © { JSL } 69 C# Programming Fundamentals Objects Relationships Systems ControlFlow
  70. 70. © { JSL } 70 Blocks  a block and its parent block  cannot have a variable with the same name  sibling blocks  can have variables with the same name int m; { int m; ... } compile time error OK { int m; ... } { int m; ... }
  71. 71. © { JSL } 71 if  no built-in conversions to/from bool  System.Convert.ToBoolean(int i) exists though  definite assignment consequences  just like in Java if (number % 2 == 0) parity = "odd"; else parity = "even"; if ( boolean-expression ) embedded-statement else embedded-statement if (number % 2 == 0) string parity = "even"; ... OK compile time error string parity = number % 2 == 0 ? "odd" : "even"; ternary operator
  72. 72. © { JSL } 72 switch  usual syntax  switch on integral types  case labels must be compile time constants  etc switch (trumps) { case Suit.Clubs: ... break; case Suit.Hearts: ... break; case Suit.Diamonds: ... break; case Suit.Spades: ... break; default: ... break; }
  73. 73. © { JSL } 73 caseNotes  unusual syntax  you can switch on a string  fall through is illegal, even on default clause  you can goto a case/default 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; } }
  74. 74. © { JSL } 74 while/do  standard 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
  75. 75. © { JSL } 75 for  for statement  declared variables are scoped to for 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
  76. 76. © { JSL } 76 foreach  from shell, VB, PERL, etc  works 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 ArrayList  C++ vector<>
  77. 77. © { JSL } 77 foreachNotes  foreach ( type identifier in expression )  type and identifier declare an iteration variable  implicitly readonly, can't be ref or out parameter  expression must be either  an IEnumerable collection, or  a "collection type"  conversion 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); }
  78. 78. © { JSL } 78 continue/break  no labelled break 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
  79. 79. © { JSL } 79 C# Programming Fundamentals Objects Relationships Systems struct
  80. 80. © { JSL } 80 structDeclaration  a user-defined value-type struct Pair { public int X, Y; }; optional semi-colon by convention public names start with an uppercase letter (PascalCase) struct Pair { private int x, y; } ...and private names start with a lowercase letter (camelCase) struct Pair { int x, y; } default access is private
  81. 81. © { JSL } 81 structCreation  a struct local variable lives on the stack  is not definitely assigned, just like int  can always 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); ... } compile time error
  82. 82. © { JSL } 82 structUse  usual dot operator to access field  field must be assigned before its value is used  default c'tor default initialises fields zero/false/null ... 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
  83. 83. © { JSL } 83 structConstructor  unusual rules  compiler declares default c'tor  you cannot declare the default c'tor  default 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
  84. 84. © { JSL } 84 :this(...)  a c'tor can call a sibling c'tor  syntax is similar to C++  no 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; }
  85. 85. © { JSL } 85 instanceFields  instance fields...  are default initialised in compilers default c'tor  must 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
  86. 86. © { JSL } 86 readonlyFields  readonly instance fields...  are 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
  87. 87. © { JSL } 87 constFields  const fields are implicitly static  only simple types, enums, & string can be const  const fields require a variable initialiser  must 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
  88. 88. © { JSL } 88 staticFields  to declare static fields of other types  use static keyword!  static fields are default initialised  static fields can use variable initialisers  access 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
  89. 89. © { JSL } 89 LocalVariables  local variables can be declared const  but not static, and not readonly  and const is only for simple types  must 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 = ...; } } compile time errors
  90. 90. © { JSL } 90 staticConstructor  a static c'tor initialises the type  can initialize static fields but not const fields  called by VES when the type is loaded  cannot 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
  91. 91. © { JSL } 91 CopyConstructor?  you can declare a "copy constructor"  it is not called for value parameters/returns  a copy is always a plain bitwise copy struct Pair { ... Pair(Pair other) { ... } ... } struct Pair { ... Pair Func() ... ... void Func(Pair copy) { Pair p = new Pair(copy); } } calling this does not result in infinite recursion these do not call the copy c'tor only this does
  92. 92. © { JSL } 92 CopyAssignment?  you cannot overload simple assignment  a copy is always 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
  93. 93. © { JSL } 93 C# Programming Fundamentals Objects Relationships Systems Operators
  94. 94. © { JSL } 94 Overloading  you can  overload most operators  you can't  create new operators  change the multiplicity or precedence  change the associativity or order of evaluation  change the meaning of built in operators unary + - ! ~ ++ -- true false binary + - * / % & | ^ << >> == != > < >= <=
  95. 95. © { JSL } 95 operatorSyntax  operators are always defined as  public static methods (never virtual)  copy parameters only (not ref-out )  one+ 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 new void Func(Meter lhs, Meter rhs) { Stuff(lhs + rhs); }
  96. 96. © { JSL } 96 Assignment  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; ... }
  97. 97. © { JSL } 97 ++--  you can overload ++ and --  a single operator supports prefix and postfix  prefix returns the result of the call  postfix 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;
  98. 98. © { JSL } 98 operatorFamilies  some operators have natural partners  you 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 == != < > <= >=
  99. 99. © { JSL } 99 operatortrue/false  designed for tri-state boolean types  eg SQL types: true, false, Null  also have the effect of  creating an implicit conversion to bool  can overload && || in combination with & | struct DBaseBool { public static bool operator false (DBbaseBool arg) ... public static bool operator true (DBbaseBool arg) ... }
  100. 100. © { JSL } 100 Conversions  must be public and static  must be implicit or explicit  implicit : compiler can call, should never throw  explicit : compiler can't call, cast required, may throw struct DBaseBool { public static implicit operator DBbaseBool (bool from) ... public static explicit operator bool (DBbaseBool from) ... }
  101. 101. © { JSL } 101 Example  "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 ... } }
  102. 102. © { JSL } 102 ConversionNotes  implicit conversion resolution  optional standard implicit conversion  user defined implicit conversion  optional standard implicit conversion  explicit conversion resolution  optional standard explicit conversion  user defined implicit or explicit conversion  optional standard explicit conversion a single argument constructor is never a converting constructor you cannot create conversions to interfaces
  103. 103. © { JSL } 103 C# Programming Fundamentals Objects Relationships Systems Indexers
  104. 104. © { JSL } 104 []  indexers provide [ ] like syntax of use  always an instance member, can be virtual  no ref-out parameters  can 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
  105. 105. © { JSL } 105 getandset  indexers can only contain accessors  get { accessor } for read context  set { accessor } for write context class DoubleArray { ... public double this [int index] { get { return ...; } set { ... = value; } } ... } marks[2] = 34.29; if (marks[0] > 50.0) ...
  106. 106. © { JSL } 106 getorset  an indexer with no set accessor  is a read-only indexer  and indexer with no get accessor  is 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
  107. 107. © { JSL } 107 IndexerNotes  indexers compared to arrays  indexers can use multiple parameters  indexers can use non integer indexes  indexers can be overloaded  indexers can be declared in an interface interface IMatrix { ... double this [int row, int col] { get; set; } ... }
  108. 108. © { JSL } 108 C# Programming Fundamentals Objects Relationships Systems Properties
  109. 109. © { JSL } 109 getandsetAgain  an object oriented smart field  get and set accessors  instance property can be virtual 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 ( ) here and capital X
  110. 110. © { JSL } 110 staticProperties  properties can be static  unlike indexers class Console { ... public static readonly TextWriter Out { get { ... } } private static TextWriter out = null; } struct DateTime { ... public static DateTime Today { get { ... } } ... } possible lazy creation
  111. 111. © { JSL } 111 PropertyNotes  properties  are not lvalues, can't be ref-out args  can't be void  can't take arbitrary parameters  can be virtual  instance properties can go in an interface interface IAccount { ... decimal Balance { get; } ... }
  112. 112. © { JSL } 112 Summary  .NET, IL, CLS, CLR, VES  stack values – enum, struct (eg int )  control flow – switch, foreach  functions  ref-out parameters  no global functions, by default not virtual  const – but only for simple types and string  operators  always public, always static  compound assignment, ++, families  conversions – implicit and explicit  get and set { accessors }  instance indexers [ ] [ , ]  instance and static properties

×