+ All Categories
Home > Documents > Csharp Language Specification v1.2

Csharp Language Specification v1.2

Date post: 03-Jun-2018
Category:
Upload: andzaone
View: 223 times
Download: 0 times
Share this document with a friend

of 409

Transcript
  • 8/12/2019 Csharp Language Specification v1.2

    1/408

    C#Language Specification

    Version 1.2

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. Please send corrections, co ents, and other feed!ac" to sharp# icrosoft.co

    1

    2

    3

    4

    5

    6

    7

    8

    9

    12

    mailto:[email protected]:[email protected]:[email protected]
  • 8/12/2019 Csharp Language Specification v1.2

    2/408

    Notice

    1999-2003 Microsoft Corporation. All rights reserved.

    Microsoft, Windows, is!al "asic, is!al C#, and is!al C$$ are either registered trade%ar&s or trade%ar&s of MicrosoftCorporation in the '.(.A. and)or other co!ntries)regions.

    *ther prod!ct and co%pan+ na%es %entioned herein %a+ e the trade%ar&s of their respective owners.

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

    1

    2

    34

    5

    1

  • 8/12/2019 Csharp Language Specification v1.2

    3/408

    Table of Contents

    Table of Contents

    1. Introduction..................................................................................................................................................... 11.1 Hello world.................................................................................................................................................. 11.2 Program structure........................................................................................................................................ 2

    1.3 Types and variables.....................................................................................................................................41.4 E pressions............................................................................................................................................... .. !1." tatements................................................................................................................................................... $1.! Classes and ob%ects....................................................................................................................................12

    1.!.1 &embers............................................................................................................................................. 131.!.2 'ccessibility................................................................................................................................. ...... 141.!.3 (ase classes........................................................................................................................................ 141.!.4 )ields.................................................................................................................................................. 141.!." &et*ods.............................................................................................................................................. 1"

    1.!.".1 Parameters.................................................................................................................................... 1"1.!.".2 &et*od body and local variables............ .......... .......... .......... ........... .......... .......... .......... ...... ..... .... 1+1.!.".3 tatic and instance met*ods............. .......... .......... ........... .......... .......... .......... .......... .......... ........ .... 1+1.!.".4 ,irtual- override- and abstract met*ods.............. .......... .......... .......... ........... .......... ....... ..... ..... ..... .11.!."." &et*od overloading.................................................................................................................... .21

    1.!.! /t*er 0unction members............ .......... .......... ........... .......... .......... .......... .......... .......... ........... .......... .... 211.!.!.1 Constructors................................................................................................................................. 241.!.!.2 Properties......................................................................................................................................2"1.!.!.3 nde ers........................................................................................................................................ 2"1.!.!.4 Events...........................................................................................................................................2!1.!.!." /perators...................................................................................................................................... 2!1.!.!.! estructors................................................................................................................................... 2+

    1.+ tructs........................................................................................................................................................2+1. 'rrays........................................................................................................................................................21.$ nter0aces...................................................................................................................................................31.1 Enums...................................................................................................................................................... 311.11 elegates.................................................................................................................................................321.12 'ttributes.................................................................................................................................................33

    2. Lexical structure......................................................................................................................................... ..352.1 Programs................................................................................................................................................... 3"2.2 rammars.................................................................................................................................................. 3"

    2.2.1 rammar notation............................................................................................................................... 3"2.2.2 5e ical grammar................................................................................................................................. 3!2.2.3 yntactic grammar........................................................................................................................... ...3!

    2.3 5e ical analysis......................................................................................................................................... 3!2.3.1 5ine terminators.................................................................................................................................. 3+2.3.2 Comments........................................................................................................................................... 3+2.3.3 6*ite space......................................................................................................................................... 3$

    2.4 To7ens.......................................................................................................................................................3$2.4.1 8nicode c*aracter escape se9uences............. .......... .......... .......... .......... .......... ........... .......... ...... .... ..... 3$2.4.2 denti0iers............................................................................................................................................ 42.4.3 :eywords............................................................................................................................................422.4.4 5iterals................................................................................................................................................42

    2.4.4.1 (oolean literals.............................................................................................................................422.4.4.2 nteger literals...............................................................................................................................432.4.4.3 ;eal literals...................................................................................................................................44

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. iii

    1

    1

    2

    3

    4

    56

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    4142

    43

    44

    45

    46

    47

    48

    49

    2

  • 8/12/2019 Csharp Language Specification v1.2

    4/408

    C# Language Specification v1.2

    2.4.4.4 C*aracter literals................................................................................................................ .......... 442.4.4." tring literals................................................................................................................................ 4"2.4.4.! T*e null literal..............................................................................................................................4+

    2.4." /perators and punctuators............... .......... .......... .......... ........... .......... .......... .......... .......... .......... ......... 4+2." Pre

  • 8/12/2019 Csharp Language Specification v1.2

    5/408

    Table of Contents

    4.2 ;e0erence types......................................................................................................................................... "4.2.1 Class types.......................................................................................................................................... !4.2.2 T*e ob%ect type.................................................................................................................................... !4.2.3 T*e string type.................................................................................................................................... !4.2.4 nter0ace types..................................................................................................................................... +4.2." 'rray types.......................................................................................................................................... +4.2.! elegate types..................................................................................................................................... +

    4.3 (o ing and unbo ing............................................................................................................................... . +4.3.1 (o ing conversions............................................................................................................................. +4.3.2 8nbo ing conversions.........................................................................................................................

    5. %ariables........................................................................................................................................................ $1".1 ,ariable categories.................................................................................................................................... $1

    ".1.1 tatic variables.................................................................................................................................... $1".1.2 nstance variables................................................................................................................................$1

    ".1.2.1 nstance variables in classes.........................................................................................................$2".1.2.2 nstance variables in structs............ .......... .......... ........... .......... .......... .......... .......... .......... ...... ..... ..$2

    ".1.3 'rray elements.................................................................................................................................... $2

    ".1.4 ,alue parameters................................................................................................................................ $2".1." ;e0erence parameters..........................................................................................................................$2".1.! /utput parameters...............................................................................................................................$2".1.+ 5ocal variables.................................................................................................................................... $3

    ".2 e0ault values............................................................................................................................................$3".3 e0inite assignment................................................................................................................................... $4

    ".3.1 nitially assigned variables.............. ........... .......... .......... .......... .......... .......... ........... .......... ......... ..... .... $"".3.2 nitially unassigned variables.............. .......... ........... .......... .......... .......... .......... .......... ........... ..... ..... .... $"".3.3 Precise rules 0or determining de0inite assignment............. .......... .......... .......... .......... ........... ....... ..... ...$"

    ".3.3.1 eneral rules 0or statements......................................................................................................... $!".3.3.2 (loc7 statements- c*ec7ed- and unc*ec7ed statements............ .......... .......... .......... ........... ........ ....$!".3.3.3 E pression statements............................................................................................................ ......$!

    ".3.3.4 eclaration statements..................................................................................................................$!".3.3." 0 statements................................................................................................................................. $+".3.3.! witc* statements.........................................................................................................................$+".3.3.+ 6*ile statements..................................................................................................................... .....$+".3.3. o statements...............................................................................................................................$+".3.3.$ )or statements.............................................................................................................................. $".3.3.1 (rea7- continue- and goto statements......................................................................................... $".3.3.11 T*row statements..................................................................................................................... ..$".3.3.12 ;eturn statements.......................................................................................................................$".3.3.13 Try

  • 8/12/2019 Csharp Language Specification v1.2

    6/408

    C# Language Specification v1.2

    ".3.3.2" @ e pressions............................................................................................................................. 1 4".3.3.2! AB e pressions...................................................................................................................... .....1 4

    ".4 ,ariable re0erences..................................................................................................................................1 ""." 'tomicity o0 variable re0erences........... .......... .......... ........... .......... .......... .......... .......... ........... .......... ...... .1 "

    &. Conversions................................................................................................................................................. 1'!

    !.1 mplicit conversions................................................................................................................................ 1 +!.1.1 dentity conversion............................................................................................................................1 +!.1.2 mplicit numeric conversions................ .......... .......... .......... ........... .......... .......... .......... ......... .... ..... ... 1 +!.1.3 mplicit enumeration conversions.............. .......... ........... .......... .......... .......... .......... ........ ..... ..... ..... ...1!.1.4 mplicit re0erence conversions...................................................................................................... ....1!.1." (o ing conversions...........................................................................................................................1!.1.! mplicit constant e pression conversions............... .......... ........... .......... .......... .......... .......... ..... ..... .... 1 $!.1.+ 8ser

  • 8/12/2019 Csharp Language Specification v1.2

    7/408

    Table of Contents

    +." Primary e pressions.................................................................................................................................132+.".1 5iterals.............................................................................................................................................. 133+.".2 imple names....................................................................................................................................133

    +.".2.1 nvariant meaning in bloc7s.................................................................................................. .....134+.".3 Parent*esi ed e pressions................................................................................................................. 13"+.".4 &ember access..................................................................................................................................13"

    +.".4.1 dentical simple names and type names......... ........... .......... .......... .......... .......... .......... ........ ..... ...13!+."." nvocation e pressions......................................................................................................................13+

    +.".".1 &et*od invocations................................................................................................................... .13++.".".2 elegate invocations............................................................................................................... ...13

    +.".! Element access.................................................................................................................................. 13$+.".!.1 'rray access............................................................................................................................... 13$+.".!.2 nde er access............................................................................................................................ 13$

    +.".+ T*is access........................................................................................................................................ 14+.". (ase access....................................................................................................................................... 141+.".$ Post0i increment and decrement operators............ .......... .......... .......... ........... .......... .......... .......... ....141+.".1 T*e new operator............................................................................................................................ 142

    +.".1 .1 /b%ect creation e pressions................. .......... .......... .......... .......... ........... .......... ......... ..... .... ..... .142+.".1 .2 'rray creation e pressions..................................................................................................... ..143+.".1 .3 elegate creation e pressions................ .......... ........... .......... .......... .......... .......... .......... ......... ...14"

    +.".11 T*e typeo0 operator.........................................................................................................................14++.".12 T*e c*ec7ed and unc*ec7ed operators........... ........... .......... .......... .......... .......... .......... ....... ..... ..... ...14+

    +.! 8nary operators.......................................................................................................................................1"+.!.1 8nary plus operator............. .......... ........... .......... .......... .......... .......... .......... ........... .......... .......... ....... .1"+.!.2 8nary minus operator.............. .......... .......... .......... ........... .......... .......... .......... .......... .......... ........... .... 1"+.!.3 5ogical negation operator................................................................................................................. 1"1+.!.4 (itwise complement operator............. .......... .......... .......... ........... .......... .......... .......... .......... .......... ....1"1+.!." Pre0i increment and decrement operators............. .......... .......... ........... .......... .......... ........ ..... .... ..... ..1"1+.!.! Cast e pressions................................................................................................................................1"2

    +.+ 'rit*metic operators................................................................................................................................1"3

    +.+.1 &ultiplication operator..................................................................................................................... 1"3+.+.2 ivision operator......................................................................................................................... .....1"4+.+.3 ;emainder operator...........................................................................................................................1""+.+.4 'ddition operator.............................................................................................................................. 1"!+.+." ubtraction operator..........................................................................................................................1"

    +. *i0t operators......................................................................................................................................... 1!+.$ ;elational and type

  • 8/12/2019 Csharp Language Specification v1.2

    8/408

  • 8/12/2019 Csharp Language Specification v1.2

    9/408

    Table of Contents

    1 .1.1 Class modi0iers.............. ........... .......... .......... .......... .......... .......... ........... .......... .......... .......... .......... ..2111 .1.1.1 'bstract classes..................................................................................................................... ...2111 .1.1.2 ealed classes...........................................................................................................................212

    1 .1.2 Class base speci0ication................ .......... .......... .......... .......... ........... .......... .......... .......... .......... ........ 2121 .1.2.1 (ase classes.............................................................................................................................. 2131 .1.2.2 nter0ace implementations........................................................................................................ 214

    1 .1.3 Class body.......................................................................................................................................2141 .2 Class members.......................................................................................................................................214

    1 .2.1 n*eritance...................................................................................................................................... 21"1 .2.2 T*e new modi0ier............................................................................................................................ 21!1 .2.3 'ccess modi0iers.............................................................................................................................21!1 .2.4 Constituent types............. .......... .......... .......... ........... .......... .......... .......... .......... .......... ........... ....... ... 21!1 .2." tatic and instance members........................................................................................................... 21!1 .2.! =ested types....................................................................................................................................21+

    1 .2.!.1 )ully 9uali0ied name.......... ........... .......... .......... .......... .......... .......... ........... .......... .......... ...... ..... 211 .2.!.2 eclared accessibility...............................................................................................................211 .2.!.3 Hiding.......................................................................................................................................21$1 .2.!.4 t*is access.................................................................................................................................21$1 .2.!." 'ccess to private and protected members o0 t*e containing type....... .......... ..... .... ..... .... ..... .....22

    1 .2.+ ;eserved member names........... .......... .......... .......... ........... .......... .......... .......... .......... ........... ........ ..2211 .2.+.1 &ember names reserved 0or properties............. .......... .......... .......... .......... ........... .......... ......... ..2211 .2.+.2 &ember names reserved 0or events..........................................................................................2221 .2.+.3 &ember names reserved 0or inde ers............ .......... .......... .......... .......... .......... .......... ..... ..... .... .2221 .2.+.4 &ember names reserved 0or destructors............. .......... ........... .......... .......... .......... ..... ..... .... ..... 223

    1 .3 Constants............................................................................................................................................... 2231 .4 )ields..................................................................................................................................................... 224

    1 .4.1 tatic and instance 0ields............ ........... .......... .......... .......... .......... ........... .......... .......... ......... ..... .... .22!1 .4.2 ;eadonly 0ields............................................................................................................................... 22!

    1 .4.2.1 8sing static readonly 0ields 0or constants.............. ........... .......... .......... .......... ........ ..... .... ..... .... 22!1 .4.2.2 ,ersioning o0 constants and static readonly 0ields........... .......... .......... .......... .......... ......... ..... ...22+

    1 .4.3 ,olatile 0ields.................................................................................................................................. 22+1 .4.4 )ield initiali ation........................................................................................................................... 221 .4." ,ariable initiali ers.........................................................................................................................22$

    1 .4.".1 tatic 0ield initiali ation.................. ........... .......... .......... .......... .......... .......... ........... .......... ........ 231 .4.".2 nstance 0ield initiali ation..................................................................................................... ..231

    1 ." &et*ods.................................................................................................................................................2311 .".1 &et*od parameters..........................................................................................................................233

    1 .".1.1 ,alue parameters...................................................................................................................... 2341 .".1.2 ;e0erence parameters............................................................................................................... 2341 .".1.3 /utput parameters........................................................................................................... .........23"1 .".1.4 Parameter arrays.......................................................................................................................23!

    1 .".2 tatic and instance met*ods........................................................................................................... .23$

    1 .".3 ,irtual met*ods...............................................................................................................................23$1 .".4 /verride met*ods............................................................................................................................2411 ."." ealed met*ods............................................................................................................................... 2431 .".! 'bstract met*ods.................................................................................................................... ........2431 .".+ E ternal met*ods.................................................................................................................... ........24"1 .". &et*od body................................................................................................................................... 24"1 .".$ &et*od overloading........................................................................................................................ 24!

    1 .! Properties...............................................................................................................................................24!1 .!.1 tatic and instance properties............... .......... .......... .......... .......... ........... .......... .......... ......... ..... .... ..24+

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. ix

    1

    1

    2

    3

    4

    5

    6

    78

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    1920

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    3132

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    4344

    45

    46

    47

    48

    49

    50

    51

    2

  • 8/12/2019 Csharp Language Specification v1.2

    10/408

    C# Language Specification v1.2

    1 .!.2 'ccessors........................................................................................................................................241 .!.3 ,irtual- sealed- override- and abstract accessors........... .......... .......... .......... .......... .... ..... ..... ..... .... ...2"2

    1 .+ Events....................................................................................................................................................2"41 .+.1 )ield

  • 8/12/2019 Csharp Language Specification v1.2

    11/408

    Table of Contents

    12.! 'rray initiali ers....................................................................................................................................2 $

    13. Interfaces................................................................................................................................................... 2$113.1 nter0ace declarations.............................................................................................................................2$1

    13.1.1 nter0ace modi0iers.......................................................................................................................... 2$113.1.2 (ase inter0aces................................................................................................................................ 2$1

    13.1.3 nter0ace body................................................................................................................................. 2$213.2 nter0ace members................................................................................................................................. 2$2

    13.2.1 nter0ace met*ods............................................................................................................................2$313.2.2 nter0ace properties......................................................................................................................... 2$413.2.3 nter0ace events...............................................................................................................................2$413.2.4 nter0ace inde ers............................................................................................................................2$413.2." nter0ace member access................................................................................................................. 2$4

    13.3 )ully 9uali0ied inter0ace member names.......... .......... .......... .......... .......... .......... ........... .......... ......... ..... .2$!13.4 nter0ace implementations............................................................................................................ .........2$+

    13.4.1 E plicit inter0ace member implementations................. .......... .......... .......... ........... .......... ....... ..... .... 2$+13.4.2 nter0ace mapping........................................................................................................................ ...2$$13.4.3 nter0ace implementation in*eritance............ ........... .......... .......... .......... .......... .......... ........ .... ..... .... 3 2

    13.4.4 nter0ace re

  • 8/12/2019 Csharp Language Specification v1.2

    12/408

  • 8/12/2019 Csharp Language Specification v1.2

    13/408

    Table of Contents

    (.1.2 6*ite space..................................................................................................................................... .3+"(.1.3 Comments.................................................................................................................................. ......3+"(.1.4 To7ens..............................................................................................................................................3+!(.1." 8nicode c*aracter escape se9uences................................................................................................3+!(.1.! denti0iers........................................................................................................................................ .3++(.1.+ :eywords......................................................................................................................................... 3+(.1. 5iterals............................................................................................................................................. 3+(.1.$ /perators and punctuators................................................................................................................ 3(.1.1 Pre

  • 8/12/2019 Csharp Language Specification v1.2

    14/408

    C0apter 2 Lexical structure

    1. Introduction

    C# pronounced I ee *arpJK is a simple- modern- ob%ect

  • 8/12/2019 Csharp Language Specification v1.2

    15/408

    C# Language Specification v1.2

    C# source 0iles typically *ave t*e 0ile e tension .cs . 'ssuming t*at t*e IHello- 6orldJ program is stored in t*e0ile ello.cs - t*e program can be compiled wit* t*e &icroso0t C# compiler using t*e command line

    csc ello.cs

    w*ic* produces an e ecutable assembly named ello.e#e . T*e output produced by t*is application w*en it isrun is

    Hello World

    T*e IHello- 6orldJ program starts wit* a using directive t*at re0erences t*e System namespace. =amespaces provide a *ierarc*ical means o0 organi ing C# programs and libraries. =amespaces contain types and ot*ernamespaces 0or e ample- t*e System namespace contains a number o0 types- suc* as t*e Console classre0erenced in t*e program- and a number o0 ot*er namespaces- suc* as $% and Collections . ' using directive t*at re0erences a given namespace enables un9uali0ied use o0 t*e types t*at are members o0 t*atnamespace. (ecause o0 t*e using directive- t*e program can use Console.WriteLine as s*ort*and 0orSystem.Console.WriteLine .

    T*e Hello class declared by t*e IHello- 6orldJ program *as a single member- t*e met*od named Main . T*eMain met*od is declared wit* t*e static modi0ier. 8nli7e instance met*ods- w*ic* re0erence a particular

    ob%ect instance using t*e 7eyword t is - static met*ods operate wit*out re0erence to a particular ob%ect. (yconvention- a static met*od named Main serves as t*e entry point o0 a program.

    T*e output o0 t*e program is produced by t*e WriteLine met*od o0 t*e Console class in t*e System namespace. T*is class is provided by t*e .=ET )ramewor7 class libraries- w*ic*- by de0ault- are automaticallyre0erenced by t*e &icroso0t C# compiler. =ote t*at C# itsel0 does not *ave a separate runtime library. nstead-t*e .=ET )ramewor7 is t*e runtime library o0 C#.

    1.2 Program structureT*e 7ey organi ational concepts in C# are progra s - na espaces - types - e !ers - and asse !lies . C#

    programs consist o0 one or more source 0iles. Programs declare types- w*ic* contain members and can beorgani ed into namespaces. Classes and inter0aces are e amples o0 types. )ields- met*ods- properties- and events

    are e amples o0 members. 6*en C# programs are compiled- t*ey are p*ysically pac7aged into assemblies.'ssemblies typically *ave t*e 0ile e tension .e#e or .dll - depending on w*et*er t*ey implement applications or li!raries .

    T*e e ample

    using System;

    names&ace 'cme.Collections{

    &ublic class Stac{

    ntry to&;

    &ublic void *us (object data) {

    to& + ne, ntry(to& data);!

    &ublic object *o&() {i- (to& ++ null) t ro, ne, $nvalid%&eration #ce&tion();object result + to&.data;to& + to&.ne#t;return result;

    !

    2 Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

    1

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    1617

    18

    19

    20

    21

    22

    23

    24

    25

    2627

    28

    29

    30

    3132333435

    36

    3738

    394041424344

    2

  • 8/12/2019 Csharp Language Specification v1.2

    16/408

    C0apter 2 Lexical structure

    class ntry{

    &ublic ntry ne#t;&ublic object data;

    &ublic ntry( ntry ne#t object data) {t is.ne#t + ne#t;

    t is.data + data;!!

    !!

    declares a class named Stac in a namespace called 'cme.Collections . T*e 0ully 9uali0ied name o0 t*isclass is 'cme.Collections.Stac . T*e class contains several membersB a 0ield named to& - two met*odsnamed *us and *o&- and a nested class named ntry . T*e ntry class 0urt*er contains t*ree membersB a0ield named ne#t - a 0ield named data - and a constructor. 'ssuming t*at t*e source code o0 t*e e ample isstored in t*e 0ile acme.cs - t*e command line

    csc t/library acme.cs

    compiles t*e e ample as a library code wit*out a Main entry pointK and produces an assembly namedacme.dll .

    'ssemblies contain e ecutable code in t*e 0orm o0 &nter ediate ang age 5K instructions- and symbolicin0ormation in t*e 0orm o0 etadata . (e0ore it is e ecuted- t*e 5 code in an assembly is automaticallyconverted to processor

  • 8/12/2019 Csharp Language Specification v1.2

    17/408

  • 8/12/2019 Csharp Language Specification v1.2

    18/408

  • 8/12/2019 Csharp Language Specification v1.2

    19/408

    C# Language Specification v1.2

    brac7ets. )or e ample- int45 is a single

  • 8/12/2019 Csharp Language Specification v1.2

    20/408

    C0apter 2 Lexical structure

    6*en an e pression contains multiple operators- t*e precedence o0 t*e operators controls t*e order in w*ic* t*eindividual operators are evaluated. )or e ample- t*e e pression # y = > is evaluated as # (y = >) becauset*e = operator *as *ig*er precedence t*an t*e operator.

    &ost operators can be overloaded . /perator overloading permits user

  • 8/12/2019 Csharp Language Specification v1.2

    21/408

    C# Language Specification v1.2

    Categor (xpression ,escription

    Primary #.m &ember access

    #(...) &et*od and delegate invocation

    #4...5 'rray and inde er access

    # Post

  • 8/12/2019 Csharp Language Specification v1.2

    22/408

    C0apter 2 Lexical structure

    5ogical '= # E y nteger bitwise '= - boolean logical '=

    5ogical G/; # F y nteger bitwise G/;- boolean logical G/;

    5ogical /; # G y nteger bitwise /;- boolean logical /;

    Conditional '= # EE y Evaluates y only i0 # is true

    Conditional /; # GG y Evaluates y only i0 # is -alse

    Conditional # y / > Evaluates y i0 # is true - > i0 # is -alse

    'ssignment # + y 'ssignment

    # op+ y Compound assignmentO supported operators are

    =+ + A+ +

  • 8/12/2019 Csharp Language Specification v1.2

    23/408

    C# Language Specification v1.2

    State*ent (xa*ple

    5ocal variabledeclaration

    static void Main() {int a;int b + 7 c + 8;a + 2;Console.WriteLine(a b c);

    !

    5ocal constantdeclaration

    static void Main() {const -loat &i + 8.2I2JK7 -;const int r + 7J;Console.WriteLine(&i = r = r);

    !

    E pression statement static void Main() {int i;i + 278; #&ression statementConsole.WriteLine(i); #&ression statementi ; #&ression statementConsole.WriteLine(i); #&ression statement

    !

    i- statement static void Main(string45 args) {i- (args.Lengt ++ 3) {

    Console.WriteLine(" o arguments");!else {

    Console.WriteLine("%ne or more arguments");!

    !

    s,itc statement static void Main(string45 args) {int n + args.Lengt ;s,itc (n) {

    case 3/Console.WriteLine(" o arguments");brea ;

    case 2/Console.WriteLine("%ne argument");brea ;

    de-ault/Console.WriteLine("{3! arguments" n);brea ;

    !!

    !

    , ile statement static void Main(string45 args) {

    int i + 3;, ile (i args.Lengt ) {Console.WriteLine(args4i5);i ;

    !!

    1' Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

    1

    2

  • 8/12/2019 Csharp Language Specification v1.2

    24/408

    C0apter 2 Lexical structure

    do statement static void Main() {string s;do {

    s + Console.NeadLine();i- (s ?+ null) Console.WriteLine(s);

    ! , ile (s ?+ null);

    !-or statement static void Main(string45 args) {

    -or (int i + 3; i args.Lengt ; i ) {Console.WriteLine(args4i5);

    !!

    -oreac statement static void Main(string45 args) {-oreac (string s in args) {

    Console.WriteLine(s);!

    !

    brea statement static void Main() {

    , ile (true) {string s + Console.NeadLine();i- (s ++ null) brea ;Console.WriteLine(s);

    !!

    continue statement static void Main(string45 args) {-or (int i + 3; i args.Lengt ; i ) {

    i- (args4i5.StartsWit (" ")) continue;Console.WriteLine(args4i5);

    !!

    goto statement static void Main(string45 args) {int i + 3;goto c ec ;loo&/Console.WriteLine(args4i 5);c ec /i- (i args.Lengt ) goto loo&;

    !

    return statement static int 'dd(int a int b) {return a b;

    !

    static void Main() {Console.WriteLine('dd(2 7));return;

    !

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. 11

    1

    2

  • 8/12/2019 Csharp Language Specification v1.2

    25/408

    C# Language Specification v1.2

    t ro, and trystatements

    static double 6ivide(double # double y) {i- (y ++ 3) t ro, ne, 6ivide9yOero #ce&tion();return # y;

    !

    static void Main(string45 args) {try {

    i- (args.Lengt ?+ 7) {t ro, ne, #ce&tion("1,o numbers rePuired");

    !double # + double.*arse(args435);double y + double.*arse(args425);Console.WriteLine(6ivide(# y));

    !catc ( #ce&tion e) {

    Console.WriteLine(e.Message);!

    !

    c ec ed andunc ec ed statements

    static void Main() {int i + int.Ma#Qalue;c ec ed {

    Console.WriteLine(i 2); #ce&tion!unc ec ed {

    Console.WriteLine(i 2); %ver-lo,!

    !

    loc statement class 'ccount{

    decimal balance;

    &ublic void Wit dra,(decimal amount) {loc (t is) {

    i- (amount D balance) {t ro, ne, #ce&tion("$nsu--icient -unds");

    !balance

  • 8/12/2019 Csharp Language Specification v1.2

    26/408

    C0apter 2 Lexical structure

    =ew classes are created using class declarations. ' class declaration starts wit* a *eader t*at speci0ies t*eattributes and modi0iers o0 t*e class- t*e name o0 t*e class- t*e base class i0 anyK- and t*e inter0acesimplemented by t*e class. T*e *eader is 0ollowed by t*e class body- w*ic* consists o0 a list o0 memberdeclarations written between t*e delimiters { and ! .

    T*e 0ollowing is a declaration o0 a simple class named *oint B

    &ublic class *oint{

    &ublic int # y;

    &ublic *oint(int # int y) {t is.# + #;t is.y + y;

    !!

    nstances o0 classes are created using t*e ne, operator- w*ic* allocates memory 0or a new instance- invo7es aconstructor to initiali e t*e instance- and returns a re0erence to t*e instance. T*e 0ollowing statements create two*oint ob%ects and store re0erences to t*ose ob%ects in two variablesB

    *oint &2 + ne, *oint(3 3);*oint &7 + ne, *oint(23 73);

    T*e memory occupied by an ob%ect is automatically reclaimed w*en t*e ob%ect is no longer in use. t is neit*ernecessary nor possible to e plicitly deallocate ob%ects in C#.

    1.&.1 (embersT*e members o0 a class are eit*er static e !ers or instance e !ers . tatic members belong to classes- andinstance members belong to ob%ects instances o0 classesK.

    T*e 0ollowing table provides an overview o0 t*e 7inds o0 members a class can contain.

    e*ber ,escription

    Constants T*e constant values associated wit* t*e class

    )ields T*e variables o0 t*e class

    &et*ods T*e computations and actions t*at can be per0ormed by t*e class

    Properties T*e actions associated wit* reading and writing named properties o0 t*e class

    nde ers T*e actions associated wit* inde ing instances o0 t*e class li7e an array

    Events T*e noti0ications t*at can be generated by t*e class

    /perators T*e conversions and e pression operators supported by t*e class

    Constructors T*e actions re9uired to initiali e instances o0 t*e class or t*e class itsel0

    estructors T*e actions to per0orm be0ore instances o0 t*e class are permanently discarded

    Types T*e nested types declared by t*e class

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. 13

    1

    1

    2

    3

    4

    5

    678

    910111213

    14

    15

    16

    1718

    19

    20

    21

    22

    23

    24

    25

    26

    2

  • 8/12/2019 Csharp Language Specification v1.2

    27/408

  • 8/12/2019 Csharp Language Specification v1.2

    28/408

    C0apter 2 Lexical structure

    ' 0ield declared wit* t*e static modi0ier de0ines a static field . ' static 0ield identi0ies e actly one storagelocation. =o matter *ow many instances o0 a class are created- t*ere is only ever one copy o0 a static 0ield.

    ' 0ield declared wit*out t*e static modi0ier de0ines an instance field . Every instance o0 a class contains aseparate copy o0 all t*e instance 0ields o0 t*at class.

    n t*e 0ollowing e ample- eac* instance o0 t*e Color class *as a separate copy o0 t*e r - g - and b instance 0ields- but t*ere is only one copy o0 t*e 9lac - W ite - Ned - reen - and 9lue static 0ieldsB

    &ublic class Color{

    &ublic static readonly Color 9lac + ne, Color(3 3 3);&ublic static readonly Color W ite + ne, Color(7JJ 7JJ 7JJ);&ublic static readonly Color Ned + ne, Color(7JJ 3 3);&ublic static readonly Color reen + ne, Color(3 7JJ 3);&ublic static readonly Color 9lue + ne, Color(3 3 7JJ);

    &rivate byte r g b;

    &ublic Color(byte r byte g byte b) {t is.r + r;t is.g + g;t is.b + b;

    !!

    's s*own in t*e previous e ample- read-only fields may be declared wit* a readonly modi0ier. 'ssignment toa readonly 0ield can only occur as part o0 t*e 0ieldNs declaration or in an instance constructor or staticconstructor in t*e same class.

    1.&.% (et,ods' ethod is a member t*at implements a computation or action t*at can be per0ormed by an ob%ect or class.

    'tatic ethods are accessed t*roug* t*e class. &nstance ethods are accessed t*roug* instances o0 t*e class.

    &et*ods *ave a possibly emptyK list o0 para eters - w*ic* represent values or variable re0erences passed to t*emet*od- and a ret rn type - w*ic* speci0ies t*e type o0 t*e value computed and returned by t*e met*od. 'met*odNs return type is void i0 it does not return a value.

    T*e signat re o0 a met*od must be uni9ue in t*e class in w*ic* t*e met*od is declared. T*e signature o0 amet*od consists o0 t*e name o0 t*e met*od and t*e number- modi0iers- and types o0 its parameters. T*esignature o0 a met*od does not include t*e return type.

    1.6.5.1 ParametersParameters are used to pass values or variable re0erences to met*ods. T*e parameters o0 a met*od get t*eiractual values 0rom t*e arg ents t*at are speci0ied w*en t*e met*od is invo7ed. T*ere are 0our 7inds o0

    parametersB value parameters- re0erence parameters- output parameters- and parameter arrays.

    ' val e para eter is used 0or input parameter passing. ' value parameter corresponds to a local variable t*atgets its initial value 0rom t*e argument t*at was passed 0or t*e parameter. &odi0ications to a value parameter donot a00ect t*e argument t*at was passed 0or t*e parameter.

    ' reference para eter is used 0or bot* input and output parameter passing. T*e argument passed 0or a re0erence parameter must be a variable- and during e ecution o0 t*e met*od- t*e re0erence parameter represents t*e samestorage location as t*e argument variable. ' re0erence parameter is declared wit* t*e re- modi0ier. T*e0ollowing e ample s*ows t*e use o0 re- parameters.

    using System;

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. 15

    1

    1

    2

    3

    4

    5

    6

    789

    10111213

    14

    151617181920

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    3738

    39

    40

    41

    42

    43

    44

    2

  • 8/12/2019 Csharp Language Specification v1.2

    29/408

    C# Language Specification v1.2

    class 1est{

    static void S,a&(re- int # re- int y) {int tem& + #;# + y;y + tem&;

    !

    static void Main() {int i + 2 j + 7;S,a&(re- i re- j);Console.WriteLine("{3! {2!" i j); %ut&uts "7 2"

    !!

    'n o tp t para eter is used 0or output parameter passing. 'n output parameter is similar to a re0erence parameter e cept t*at t*e initial value o0 t*e caller

  • 8/12/2019 Csharp Language Specification v1.2

    30/408

  • 8/12/2019 Csharp Language Specification v1.2

    31/408

    C# Language Specification v1.2

    &ublic int etSerial o() {return serial o;

    !

    &ublic static int et e#tSerial o() {return ne#tSerial o;

    !

    &ublic static void Set e#tSerial o(int value) {ne#tSerial o + value;

    !!

    Eac* ntity instance contains a serial number and presumably some ot*er in0ormation t*at is not s*own*ereK. T*e ntity constructor w*ic* is li7e an instance met*odK initiali es t*e new instance wit* t*e ne tavailable serial number. (ecause t*e constructor is an instance member- it is permitted to access bot* t*eserial o instance 0ield and t*e ne#tSerial o static 0ield.

    T*e et e#tSerial o and Set e#tSerial o static met*ods can access t*e ne#tSerial o static 0ield- butit would be an error 0or t*em to access t*e serial o instance 0ield.

    T*e 0ollowing e ample s*ows t*e use o0 t*e ntity class.using System;

    class 1est{

    static void Main() {ntity.Set e#tSerial o(2333);

    ntity e2 + ne, ntity();ntity e7 + ne, ntity();

    Console.WriteLine(e2. etSerial o()); %ut&uts "2333"Console.WriteLine(e7. etSerial o()); %ut&uts "2332"Console.WriteLine( ntity. et e#tSerial o()); %ut&uts "2337"

    !!

    =ote t*at t*e Set e#tSerial o and et e#tSerial o static met*ods are invo7ed on t*e class w*ereas t*eetSerial o instance met*od is invo7ed on instances o0 t*e class.

    1.6.5.4 irt!al" override" and abstract methods6*en an instance met*od declaration includes a virtual modi0ier- t*e met*od is said to be a virt al ethod .6*en no virtual modi0ier is present- t*e met*od is said to be a non-virt al ethod .

    6*en a virtual met*od is invo7ed- t*e r nti e type o0 t*e instance 0or w*ic* t*at invocation ta7es placedetermines t*e actual met*od implementation to invo7e. n a nonvirtual met*od invocation- t*e co pile-ti etype o0 t*e instance is t*e determining 0actor.

    ' virtual met*od can be overridden in a derived class. 6*en an instance met*od declaration includes anoverride modi0ier- t*e met*od overrides an in*erited virtual met*od wit* t*e same signature. 6*ereas avirtual met*od declaration introd!ces a new met*od- an override met*od declaration speciali es an e istingin*erited virtual met*od by providing a new implementation o0 t*at met*od.

    'n a!stract met*od is a virtual met*od wit* no implementation. 'n abstract met*od is declared wit* t*eabstract modi0ier and is permitted only in a class t*at is also declared abstract . 'n abstract met*od must

    be overridden in every non

  • 8/12/2019 Csharp Language Specification v1.2

    32/408

    C0apter 2 Lexical structure

    T*e 0ollowing e ample declares an abstract class- #&ression - w*ic* represents an e pression tree node- andt*ree derived classes- Constant - QariableNe-erence - and %&eration - w*ic* implement e pression treenodes 0or constants- variable re0erences- and arit*metic operations.

    using System;using System.Collections;

    &ublic abstract class #&ression{&ublic abstract double valuate(Has table vars);

    !

    &ublic class Constant/ #&ression{

    double value;

    &ublic Constant(double value) {t is.value + value;

    !

    &ublic override double valuate(Has table vars) {return value;

    !!

    &ublic class QariableNe-erence/ #&ression{

    string name;

    &ublic QariableNe-erence(string name) {t is.name + name;

    !

    &ublic override double valuate(Has table vars) {object value + vars4name5;i- (value ++ null) {

    t ro, ne, #ce&tion(":n no,n variable/ " name);!return Convert.1o6ouble(value);

    !!

    &ublic class %&eration/ #&ression{

    #&ression le-t;c ar o&;

    #&ression rig t;

    &ublic %&eration( #&ression le-t c ar o& #&ression rig t) {t is.le-t + le-t;t is.o& + o&;

    t is.rig t + rig t;!

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. 1$

    1

    1

    2

    3

    45

    6789

    101112

    131415

    1617

    1819

    202122

    232425

    26272829

    30313233

    3435363738

    394041

    4243

    2

  • 8/12/2019 Csharp Language Specification v1.2

    33/408

    C# Language Specification v1.2

    &ublic override double valuate(Has table vars) {double # + le-t. valuate(vars);double y + rig t. valuate(vars);s,itc (o&) {

    case T T/ return # y;case T

  • 8/12/2019 Csharp Language Specification v1.2

    34/408

    C0apter 2 Lexical structure

    vars4"#"5 + 2.J;vars4"y"5 + K;Console.WriteLine(e. valuate(vars)); %ut&uts "2U.J"

    !!

    1.6.5.5 Method overloadin#&et*od overloading permits multiple met*ods in t*e same class to *ave t*e same name as long as t*ey *aveuni9ue signatures. 6*en compiling an invocation o0 an overloaded met*od- t*e compiler uses overloadresol tion to determine t*e speci0ic met*od to invo7e. /verload resolution 0inds t*e one met*od t*at bestmatc*es t*e arguments or reports an error i0 no single best matc* can be 0ound. T*e 0ollowing e ample s*owsoverload resolution in e00ect. T*e comment 0or eac* invocation in t*e Main met*od s*ows w*ic* met*od isactually invo7ed.

    class 1est{

    static void R() {...!Console.WriteLine("R()");

    !

    static void R(object #) {Console.WriteLine("R(object)");

    !

    static void R(int #) {Console.WriteLine("R(int)");

    !

    static void R(double #) {Console.WriteLine("R(double)");

    !

    static void R(double # double y) {Console.WriteLine("R(double double)");

    !static void Main() {

    R(); $nvo es R()R(2); $nvo es R(int)R(2.3); $nvo es R(double)R("abc"); $nvo es R(object)R((double)2); $nvo es R(double)R((object)2); $nvo es R(object)R(2 2); $nvo es R(double double)

    !!

    's s*own by t*e e ample- a particular met*od can always be selected by e plicitly casting t*e arguments to t*ee act parameter types.

    1.&.& -t,er function members&embers t*at contain e ecutable code are collectively 7nown as t*e f nction e !ers o0 a class. T*e

    preceding section describes met*ods- w*ic* are t*e primary 7ind o0 0unction members. T*is section describest*e ot*er 7inds o0 0unction members supported by C#B constructors- properties- inde ers- events- operators- anddestructors.

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. 21

    1

    12345

    67

    8

    9

    10

    11

    12

    1314151617

    181920

    212223

    242526

    272829

    30313233343536373839

    40

    41

    42

    43

    44

    45

    46

    2

  • 8/12/2019 Csharp Language Specification v1.2

    35/408

    C# Language Specification v1.2

    T*e 0ollowing table s*ows a class called List - w*ic* implements a growable list o0 ob%ects. T*e class containsseveral e amples o0 t*e most common 7inds o0 0unction members.

    22 Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

    1

    1

    2

    3

    2

  • 8/12/2019 Csharp Language Specification v1.2

    36/408

    C0apter 2 Lexical structure

    &ublic class List{

    const int de-aultCa&acity + I; Constant

    object45 items;int count;

    )ields

    &ublic List()/ List(de-aultCa&acity) {!

    &ublic List(int ca&acity) {items + ne, object4ca&acity5;

    !

    Constructors

    &ublic int Count {get { return count; !

    !

    &ublic string Ca&acity {get {

    return items.Lengt ;!

    set {i- (value count) value + count;i- (value ?+ items.Lengt ) {

    object45 ne,$tems + ne, object4value5;'rray.Co&y(items 3 ne,$tems 3 count);items + ne,$tems;

    !!

    !

    Properties

    &ublic object t is4int inde#5 {get {

    return items4inde#5;!

    set {items4inde#5 + value;%nListC ange();

    !!

    nde er

    Copyright Microsoft Corporation 1999-2003. All Rights Reserved. 23

    1

    2

  • 8/12/2019 Csharp Language Specification v1.2

    37/408

    C# Language Specification v1.2

    &ublic void 'dd(object item) {i- (count ++ Ca&acity) Ca&acity + count = 7;items4count5 + item;count ;%nC anged();

    !

    &rotected virtual void %nC anged() {i- (C anged ?+ null) C anged(t is vent'rgs. m&ty);

    !

    &ublic override bool Puals(object ot er) {return Puals(t is ot er as List);

    !

    static bool Puals(List a List b) {i- (a ++ null) return b ++ null;i- (b ++ null GG a.count ?+ b.count) return -alse;-or (int i + 3; i a.count; i ) {

    i- (?object. Puals(a.items4i5 b.items4i5)) {return -alse;

    !!!

    &et*ods

    &ublic event ventHandler C anged; Event

    &ublic static bool o&erator ++(List a List b) {return Puals(a b);

    !

    &ublic static bool o&erator ?+(List a List b) {return ? Puals(a b);

    !

    /perators

    !

    1.6.6.1 $onstr!ctorsC# supports bot* instance and static constructors. 'n instance constr ctor is a member t*at implements t*eactions re9uired to initiali e an instance o0 a class. ' static constr ctor is a member t*at implements t*e actionsre9uired to initiali e a class itsel0 w*en it is 0irst loaded.

    ' constructor is declared li7e a met*od wit* no return type and t*e same name as t*e containing class. 0 aconstructor declaration includes a static modi0ier- it declares a static constructor. /t*erwise- it declares aninstance constructor.

    nstance constructors can be overloaded. )or e ample- t*e List class declares two instance constructors- onewit* no parameters and one t*at ta7es an int parameter. nstance constructors are invo7ed using t*e ne,

    operator. T*e 0ollowing statements allocate two List instances using eac* o0 t*e constructors o0 t*e List class.List list2 + ne, List();List list7 + ne, List(23);

    8nli7e ot*er members- instance constructors are not in*erited- and a class *as no instance constructors ot*ert*an t*ose actually declared in t*e class. 0 no instance constructor is supplied 0or a class- t*en an empty onewit* no parameters is automatically provided.

    2" Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

    1

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    1213

    14

    15

    16

    2

  • 8/12/2019 Csharp Language Specification v1.2

    38/408

    C0apter 2 Lexical structure

    1.6.6.2 Pro%erties Properties are a natural e tension o0 0ields. (ot* are named members wit* associated types- and t*e synta 0oraccessing 0ields and properties is t*e same. However- unli7e 0ields- properties do not denote storage locations.

    nstead- properties *ave accessors t*at speci0y t*e statements to be e ecuted w*en t*eir values are read orwritten.

    ' property is declared li7e a 0ield- e cept t*at t*e declaration ends wit* a get accessor andMor a set accessorwritten between t*e delimiters { and ! instead o0 ending in a semicolon. ' property t*at *as bot* a get accessorand a set accessor is a read- rite property - a property t*at *as only a get accessor is a read-only property - anda property t*at *as only a set accessor is a rite-only property .

    ' get accessor corresponds to a parameterless met*od wit* a return value o0 t*e property type. E cept as t*etarget o0 an assignment- w*en a property is re0erenced in an e pression- t*e get accessor o0 t*e property isinvo7ed to compute t*e value o0 t*e property.

    ' set accessor corresponds to a met*od wit* a single parameter named value and no return type. 6*en a property is re0erenced as t*e target o0 an assignment or as t*e operand o0 or

  • 8/12/2019 Csharp Language Specification v1.2

    39/408

  • 8/12/2019 Csharp Language Specification v1.2

    40/408

    C0apter 2 Lexical structure

    class 1est{

    static void Main() {List a + ne, List();a.'dd(2);a.'dd(7);List b + ne, List();b.'dd(2);b.'dd(7);Console.WriteLine(a ++ b); %ut&uts "1rue"b.'dd(8);Console.WriteLine(a ++ b); %ut&uts "Ralse"

    !!

    T*e 0irst Console.WriteLine outputs 1rue because t*e two lists contain t*e same number o0 ob%ects wit* t*esame values. Had List not de0ined o&erator ++ - t*e 0irst Console.WriteLine would *ave output Ralse

    because a and b re0erence di00erent List instances.

    1.6.6.6 *estr!ctors' destr ctor is a member t*at implements t*e actions re9uired to destruct an instance o0 a class. estructorscannot *ave parameters- t*ey cannot *ave accessibility modi0iers- and t*ey cannot be invo7ed e plicitly. T*edestructor 0or an instance is invo7ed automatically during garbage collection.

    T*e garbage collector is allowed wide latitude in deciding w*en to collect ob%ects and run destructors.peci0ically- t*e timing o0 destructor invocations is not deterministic- and destructors may be e ecuted on any

    t*read. )or t*ese and ot*er reasons- classes s*ould implement destructors only w*en no ot*er solutions are0easible.

    1. Structs5i7e classes- str cts are data structures t*at can contain data members and 0unction members- but unli7e classes-

    structs are value types and do not re9uire *eap allocation. ' variable o0 a struct type directly stores t*e data o0t*e struct- w*ereas a variable o0 a class type stores a re0erence to a dynamically allocated ob%ect. truct types donot support user

  • 8/12/2019 Csharp Language Specification v1.2

    41/408

    C# Language Specification v1.2

    class 1est{

    static void Main() {*oint45 &oints + ne, *oint42335;-or (int i + 3; i 233; i ) &oints4i5 + ne, *oint(i i);

    !!

    'n alternative is to ma7e *oint a struct.

    struct *oint{

    &ublic int # y;

    &ublic *oint(int # int y) {t is.# + #;t is.y + y;

    !!

    =ow- only one ob%ect is instantiated t*e one 0or t*e array and t*e *oint instances are stored in

  • 8/12/2019 Csharp Language Specification v1.2

    42/408

    C0apter 2 Lexical structure

    T*e 0ollowing e ample creates an array o0 int elements- initiali es t*e array- and prints out t*e contents o0 t*earray.

    using System;

    class 1est{

    static void Main() {int45 a + ne, int4235;-or (int i + 3; i a.Lengt ; i ) a4i5 + i = i;-or (int i + 3; i a.Lengt ; i ) {

    Console.WriteLine("a4{3!5 + {2!" i a4i5);!

    !!

    T*is e ample creates and operates on a single-di ensional array . C# also supports lti-di ensional arrays .T*e number o0 dimensions o0 an array type- also 7nown as t*e ran" o0 t*e array type- is one plus t*e number o0commas written between t*e s9uare brac7ets o0 t*e array type. T*e 0ollowing e ample allocates a one + {7!" # y >);

    !

    static void Main() {int i + 3;R(i i i );

    !!

    produces t*e output

    # + 3 y + 2 > + 7

    T*e array co

  • 8/12/2019 Csharp Language Specification v1.2

    137/408

  • 8/12/2019 Csharp Language Specification v1.2

    138/408

    C# Language Specification v1.2

    0 t*e class- struct- or inter0ace in w*ic* t*e 0unction member is declared already contains anot*er applicable0unction member wit* t*e same signature as t*e e panded 0orm- t*e e panded 0orm is not applicable.

    /t*erwise- t*e e panded 0orm is applicable i0 0or eac* argument in ' t*e parameter passing mode o0 t*eargument is identical to t*e parameter passing mode o0 t*e corresponding parameter- and

    o 0or a 0i ed value parameter or a value parameter created by t*e e pansion- an implicit conversion !.1 Ke ists 0rom t*e type o0 t*e argument to t*e type o0 t*e corresponding parameter- or

    o 0or a re- or out parameter- t*e type o0 t*e argument is identical to t*e type o0 t*e corresponding parameter.

    7.4.2.2 +etter !nction member iven an argument list ' wit* a set o0 argument types [ ' 2- ' 7- ...- ' \ and two applicable 0unction members M*

    and M wit* parameter types [ * 2- * 7- ...- * \ and [ ^ 2- ^ 7- ...- ^ \- M* is de0ined to be a !etter f nction e !er t*an M i0

    0or eac* argument- t*e implicit conversion 0rom ' ] to * ] is not worse t*an t*e implicit conversion 0rom ' ] to^ ] - and

    0or at least one argument- t*e conversion 0rom ' ] to * ] is better t*an t*e conversion 0rom ' ] to ^ ] .

    6*en per0orming t*is evaluation- i0 M* or M is applicable in its e panded 0orm- t*en * ] or ^ ] re0ers to a parameter in t*e e panded 0orm o0 t*e parameter list.

    7.4.2.3 +etter conversioniven an implicit conversion C2 t*at converts 0rom a type S to a type 1 2- and an implicit conversion C7 t*at

    converts 0rom a type S to a type 1 7- t*e !etter conversion o0 t*e two conversions is determined as 0ollowsB

    01 2 and 1 7 are t*e same type- neit*er conversion is better.

    0S is 1 2- C2 is t*e better conversion.

    0S is 1 7- C7 is t*e better conversion.

    0 an implicit conversion 0rom 1 2 to 1 7 e ists- and no implicit conversion 0rom 1 7 to 1 2 e ists- C2 is t*e betterconversion.

    0 an implicit conversion 0rom 1 7 to 1 2 e ists- and no implicit conversion 0rom 1 2 to 1 7 e ists- C7 is t*e betterconversion.

    01 2 is sbyte and 1 7 is byte - us ort - uint - or ulong - C2 is t*e better conversion.

    01 7 is sbyte and 1 2 is byte - us ort - uint - or ulong - C7 is t*e better conversion.

    01 2 is s ort and 1 7 is us ort - uint - or ulong - C2 is t*e better conversion.

    01 7 is s ort and 1 2 is us ort - uint - or ulong - C7 is t*e better conversion. 01 2 is int and 1 7 is uint - or ulong - C2 is t*e better conversion.

    01 7 is int and 1 2 is uint - or ulong - C7 is t*e better conversion.

    01 2 is long and 1 7 is ulong - C2 is t*e better conversion.

    01 7 is long and 1 2 is ulong - C7 is t*e better conversion.

    /t*erwise- neit*er conversion is better.

    13' Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

    1

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    2

  • 8/12/2019 Csharp Language Specification v1.2

    139/408

    C0apter 2 Lexical structure

    0 an implicit conversion C2 is de0ined by t*ese rules to be a better conversion t*an an implicit conversion C7-t*en it is also t*e case t*at C7 is a orse conversion t*an C2.

    .".3 +unction member in!ocationT*is section describes t*e process t*at ta7es place at run

  • 8/12/2019 Csharp Language Specification v1.2

    140/408

    C# Language Specification v1.2

    determined by applying t*e inter0ace mapping rules 13.4.2 K to determine t*e implementation o0 M provided by t*e run

  • 8/12/2019 Csharp Language Specification v1.2

    141/408

    C0apter 2 Lexical structure

    Primary e pressions are divided between arra+-creation-e/pressions and pri%ar+-no-arra+-creation-e/pression s. Treating array

  • 8/12/2019 Csharp Language Specification v1.2

    142/408

  • 8/12/2019 Csharp Language Specification v1.2

    143/408

    C0apter 2 Lexical structure

    &ublic *oint(int # int y) {t is.# + #;t is.y + y;

    !!

    T*e e ample above illustrates a common pattern o0 using t*e names o0 0ields as parameter names in an instanceconstructor. n t*e e ample- t*e simple names # and y re0er to t*e parameters- but t*at does not prevent t*emember access e pressions t is.# and t is.y 0rom accessing t*e 0ields.

    .%.3 Parent,esi

  • 8/12/2019 Csharp Language Specification v1.2

    144/408

    C# Language Specification v1.2

    0 t*e re0erence occurs wit*in t*e class or struct in w*ic* t*e event is declared- and t*e event wasdeclared wit*out event-accessor-declarations 1 .+K- t*en .$ is processed e actly as i0 $ was astatic 0ield.

    /t*erwise- t*e result is an event access wit* no associated instance e pression.

    o 0$ identi0ies a constant- t*en t*e result is a value- namely t*e value o0 t*at constant.

    o 0$ identi0ies an enumeration member- t*en t*e result is a value- namely t*e value o0 t*at enumerationmember.

    o /t*erwise- .$ is an invalid member re0erence- and a compile

  • 8/12/2019 Csharp Language Specification v1.2

    145/408

    C0apter 2 Lexical structure

    to t*e static members and nested types o0 w*ere a compile

  • 8/12/2019 Csharp Language Specification v1.2

    146/408

    C# Language Specification v1.2

    T*e set o0 candidate met*ods 0or t*e met*od invocation is constructed. tarting wit* t*e set o0 met*odsassociated wit* M- w*ic* were 0ound by a previous member loo7up +.3K- t*e set is reduced to t*osemet*ods t*at are applicable wit* respect to t*e argument list ' . T*e set reduction consists o0 applying t*e0ollowing rules to eac* met*od 1. in t*e set- w*ere 1 is t*e type in w*ic* t*e met*od is declaredB

    o 0 is not applicable wit* respect to ' +.4.2.1 K- t*en is removed 0rom t*e set.

    o 0 is applicable wit* respect to ' +.4.2.1 K- t*en all met*ods declared in a base type o0 1 are removed0rom t*e set.

    0 t*e resulting set o0 candidate met*ods is empty- t*en no applicable met*ods e ist- and a compile

  • 8/12/2019 Csharp Language Specification v1.2

    147/408

    C0apter 2 Lexical structure

    .%.& #lement access'n ele%ent-access consists o0 a pri%ar+-no-arra+-creation-e/pression - 0ollowed by a I 4 I to7en- 0ollowed by ane/pression-list - 0ollowed by a I 5J to7en. T*e e/pression-list consists o0 one or more e/pression s- separated bycommas.

    ele%ent-access

    pri%ar+-no-arra+-creation-e/pression = e/pression-list >e/pression-list

    e/pressione/pression-list ? e/pression

    0 t*e pri%ar+-no-arra+-creation-e/pression o0 an ele%ent-access is a value o0 an arra+-t+pe - t*e ele%ent-access is an array access +.".!.1 K. /t*erwise- t*e pri%ar+-no-arra+-creation-e/pression must be a variable orvalue o0 a class- struct- or inter0ace type t*at *as one or more inde er members- in w*ic* case t*e ele%ent-access is an inde er access +.".!.2 K.

    7.5.6.1 >rray access)or an array access- t*e pri%ar+-no-arra+-creation-e/pression o0 t*e ele%ent-access must be a value o0 anarra+-t+pe . T*e number o0 e pressions in t*e e/pression-list must be t*e same as t*e ran7 o0 t*e arra+-t+pe - andeac* e pression must be o0 type int - uint - long - ulong - or o0 a type t*at can be implicitly converted to one ormore o0 t*ese types.

    T*e result o0 evaluating an array access is a variable o0 t*e element type o0 t*e array- namely t*e array elementselected by t*e value sK o0 t*e e pression sK in t*e e/pression-list .

    T*e run

  • 8/12/2019 Csharp Language Specification v1.2

    148/408

    C# Language Specification v1.2

    T*e compile

  • 8/12/2019 Csharp Language Specification v1.2

    149/408

    C0apter 2 Lexical structure

    6*en t is is used in a pri%ar+-e/pression wit*in an instance met*od or instance accessor o0 a struct- it isclassi0ied as a variable. T*e type o0 t*e variable is t*e struct wit*in w*ic* t*e usage occurs- and t*e variablerepresents t*e struct 0or w*ic* t*e met*od or accessor was invo7ed. T*e t is variable o0 an instancemet*od o0 a struct be*aves e actly t*e same as a re- parameter o0 t*e struct type.

    8se o0 t is in a pri%ar+-e/pression in a conte t ot*er t*an t*e ones listed above is a compile

  • 8/12/2019 Csharp Language Specification v1.2

    150/408

    C# Language Specification v1.2

    T*e run

  • 8/12/2019 Csharp Language Specification v1.2

    151/408

    C0apter 2 Lexical structure

    T*e compile

  • 8/12/2019 Csharp Language Specification v1.2

    152/408

    C# Language Specification v1.2

    or ulong - or o0 a type t*at can be implicitly converted to one or more o0 t*ese types. T*e value o0 eac*e pression determines t*e lengt* o0 t*e corresponding dimension in t*e newly allocated array instance. incet*e lengt* o0 an array dimension must be nonnegative- it is a compile

  • 8/12/2019 Csharp Language Specification v1.2

    153/408

    C0apter 2 Lexical structure

    int4545 a + ne, int4233545;-or (int i + 3; i 233; i ) a4i5 + ne, int4J5;

    6*en an array o0 arrays *as a IrectangularJ s*ape- t*at is w*en t*e sub

  • 8/12/2019 Csharp Language Specification v1.2

    154/408

    C# Language Specification v1.2

    o 0 t*e met*od selected at compile

  • 8/12/2019 Csharp Language Specification v1.2

    155/408

    C0apter 2 Lexical structure

    t*e '.- 0ield is initiali ed wit* a delegate t*at re0ers to t*e second SPuare met*od because t*at met*od e actlymatc*es t*e 0ormal parameter list and return type o0 6oubleRunc . Had t*e second SPuare met*od not been

    present- a compile

  • 8/12/2019 Csharp Language Specification v1.2

    156/408

    C# Language Specification v1.2

    chec&ed-e/pression&he& ed ( e/pression )

    !nchec&ed-e/pressionu &he& ed ( e/pression )

    T*e c ec ed operator evaluates t*e contained e pression in a c*ec7ed conte t- and t*e unc ec ed operator

    evaluates t*e contained e pression in an unc*ec7ed conte t. ' chec&ed-e/pression or !nchec&ed-e/pression corresponds e actly to a parenthesi ed-e/pression +.".3 K- e cept t*at t*e contained e pression is evaluated int*e given over0low c*ec7ing conte t.

    T*e over0low c*ec7ing conte t can also be controlled t*roug* t*e c ec ed and unc ec ed statements .11K.

    T*e 0ollowing operations are a00ected by t*e over0low c*ec7ing conte t establis*ed by t*e c ec ed andunc ec ed operators and statementsB

    T*e prede0ined and

  • 8/12/2019 Csharp Language Specification v1.2

    157/408

    C0apter 2 Lexical structure

    static int H() {return # = y; 6e&ends on de-ault

    !!

    no compile

  • 8/12/2019 Csharp Language Specification v1.2

    158/408

    C# Language Specification v1.2

    &ublic const int Hig 9it + unc ec ed((int)3#V3333333);!

    (ot* o0 t*e *e adecimal constants above are o0 type uint . (ecause t*e constants are outside t*e int range-wit*out t*e unc ec ed operator- t*e casts to int would produce compile

  • 8/12/2019 Csharp Language Specification v1.2

    159/408

  • 8/12/2019 Csharp Language Specification v1.2

    160/408

    C# Language Specification v1.2

    pre-decre%ent-e/pression:: !nar+-e/pression

    T*e operand o0 a pre0i increment or decrement operation must be an e pression classi0ied as a variable- a property access- or an inde er access. T*e result o0 t*e operation is a value o0 t*e same type as t*e operand.

    0 t*e operand o0 a pre0i increment or decrement operation is a property or inde er access- t*e property orinde er must *ave bot* a get and a set accessor. 0 t*is is not t*e case- a compile

  • 8/12/2019 Csharp Language Specification v1.2

    161/408

    C0apter 2 Lexical structure

    T*e grammar 0or a cast-e/pression leads to certain syntactic ambiguities. )or e ample- t*e e pression (#)By could eit*er be interpreted as a cast-e/pression a cast o0 By to type #K or as an additive-e/pression combinedwit* a parenthesi ed-e/pression w*ic* computes t*e value # B y) .

    To resolve cast-e/pression ambiguities- t*e 0ollowing rule e istsB ' se9uence o0 one or more to&ens 2.3.3 Kenclosed in parent*eses is considered t*e start o0 a cast-e/pression only i0 at least one o0 t*e 0ollowing are trueB

    T*e se9uence o0 to7ens is correct grammar 0or a t+pe- but not 0or an e/pression .

    T*e se9uence o0 to7ens is correct grammar 0or a t+pe- and t*e to7en immediately 0ollowing t*e closing parent*eses is t*e to7en I @J- t*e to7en I ? J- t*e to7en I ( J- an identifier 2.4.1 K- aliteral 2.4.4 K- or any&e+word 2.4.3 K e ceptas and is .

    T*e term Icorrect grammarJ above means only t*at t*e se9uence o0 to7ens must con0orm to t*e particulargrammatical production. t speci0ically does not consider t*e actual meaning o0 any constituent identi0iers. )ore ample- i0 # and y are identi0iers- t*en #.y is correct grammar 0or a type- even i0 #.y doesnNt actually denote atype.

    )rom t*e disambiguation rule it 0ollows t*at- i0 # and y are identi0iers- (#)y - (#)(y) - and (#)(

  • 8/12/2019 Csharp Language Specification v1.2

    162/408

    C# Language Specification v1.2

    )loating

  • 8/12/2019 Csharp Language Specification v1.2

    163/408

    C0apter 2 Lexical structure

    System.'rit metic #ce&tion or a subclass t*ereo0K is t*rown or t*e over0low goes unreported wit*t*e resulting value being t*at o0 t*e le0t operand.

    )loating

  • 8/12/2019 Csharp Language Specification v1.2

    164/408

    C# Language Specification v1.2

    )loating is t*e result o0 # A y and is computed as # B n =y - w*ere n is t*e largest possible integer t*at is less t*an or e9ual to # y . T*is met*od o0 computing t*eremainder is analogous to t*at used 0or integer operands- but di00ers 0rom t*e EEE +"4 de0inition in w*ic*n is t*e integer closest to # yK.

    y By 3 B3 B a

    # > > a a # # a

    B# B> B> a a B# B# a

    3 3 3 a a 3 3 a

    B3 B3 B3 a a B3 B3 a

    a a a a a a a

    B a a a a a a a

    a a a a a a a a

    ecimal remainderB

    decimal o&erator A(decimal # decimal y);

    0 t*e value o0 t*e rig*t operand is ero- a System.6ivide9yOero #ce&tion is t*rown. T*e scale o0 t*eresult- be0ore any rounding- is t*e larger o0 t*e scales o0 t*e two operands- and t*e sign o0 t*e result- i0 non is t*e result o0 # y . 0# and y *ave t*e same magnitude but opposite signs- > is positive ero. 0

    #

    y is too large to represent in t*e destination type-

    > is an in0inity wit* t*e same sign as

    # y .

    y 3 B3 B a

    # > # # B a

    3 y 3 3 B a

    B3 y 3 B3 B a

    a a

    B B B B a B a

    a a a a a a a

    ecimal additionB

    decimal o&erator (decimal # decimal y);

    0 t*e resulting value is too large to represent in t*e decimal 0ormat- a System.%ver-lo, #ce&tion ist*rown. T*e scale o0 t*e result- be0ore any rounding- is t*e larger o0 t*e scales o0 t*e two operands.

    ecimal addition is e9uivalent to using t*e addition operator o0 type System.6ecimal .

    Enumeration addition. Every enumeration type implicitly provides t*e 0ollowing prede0ined operators-w*ere is t*e enum type- and : is t*e underlying type o0 B

    o&erator ( # : y);

    o&erator (: # y);T*e operators are evaluated e actly as ( )((:)# (:)y) .

    tring concatenationB

    string o&erator (string # string y);string o&erator (string # object y);string o&erator (object # string y);

    T*e binary operator per0orms string concatenation w*en one or bot* operands are o0 type string . 0 anoperand o0 string concatenation is null - an empty string is substituted. /t*erwise- any non

  • 8/12/2019 Csharp Language Specification v1.2

    166/408

  • 8/12/2019 Csharp Language Specification v1.2

    167/408

    C0apter 2 Lexical structure

    are non ero 0inite values- and > is t*e result o0 # B y . 0# and y are e9ual- > is positive ero. 0 # B y is toolarge to represent in t*e destination type- > is an in0inity wit* t*e same sign as # B y .

    y 3 B3 B a

    # > # # B a

    3 By 3 3 B a

    B3 By B3 3 B a

    a a

    B B B B B a a

    a a a a a a a

    ecimal subtractionB

    decimal o&erator B(decimal # decimal y);

    0 t*e resulting value is too large to represent in t*e decimal 0ormat- a System.%ver-lo, #ce&tion is

    t*rown. T*e scale o0 t*e result- be0ore any rounding- is t*e larger o0 t*e scales o0 t*e two operands.ecimal subtraction is e9uivalent to using t*e subtraction operator o0 type System.6ecimal .

    Enumeration subtraction. Every enumeration type implicitly provides t*e 0ollowing prede0ined operator-w*ere is t*e enum type- and : is t*e underlying type o0 B

    : o&erator B( # y);

    T*is operator is evaluated e actly as (:)((:)# B (:)y) . n ot*er words- t*e operator computes t*edi00erence between t*e ordinal values o0 # and y - and t*e type o0 t*e result is t*e underlying type o0 t*eenumeration.

    o&erator B( # : y);

    T*is operator is evaluated e actly as ( )((:)# B y) . n ot*er words- t*e operator subtracts a value 0romt*e underlying type o0 t*e enumeration- yielding a value o0 t*e enumeration.

    elegate removal. Every delegate type implicitly provides t*e 0ollowing prede0ined operator- w*ere 6 is t*edelegate typeB

    6 o&erator B(6 # 6 y);

    T*e binary B operator per0orms delegate removal w*en bot* operands are o0 some delegate type 6 . 0 t*eoperands *ave di00erent delegate types- a compile

  • 8/12/2019 Csharp Language Specification v1.2

    168/408

    C# Language Specification v1.2

    class C{

    &ublic static void M2(int i) { = = !&ublic static void M7(int i) { = = !

    !

    class 1est

    { static void Main() {6 cd2 + ne, 6(C.M2);6 cd7 + ne, 6(C.M7);6 cd8 + cd2 cd7 cd7 cd2; M2 M7 M7 M2cd8

  • 8/12/2019 Csharp Language Specification v1.2

    169/408

    C0apter 2 Lexical structure

    int o&erator DD(int # int count);uint o&erator DD(uint # int count);long o&erator DD(long # int count);ulong o&erator DD(ulong # int count);

    T*e DD operator s*i0ts # rig*t by a number o0 bits computed as described below.

    6*en # is o0 type int or long - t*e low

  • 8/12/2019 Csharp Language Specification v1.2

    170/408

  • 8/12/2019 Csharp Language Specification v1.2

    171/408

    C0apter 2 Lexical structure

    bool o&erator ?+(-loat # -loat y);bool o&erator ?+(double # double y);

    bool o&erator (-loat # -loat y);bool o&erator (double # double y);

    bool o&erator D(-loat # -loat y);bool o&erator D(double # double y);

    bool o&erator +(-loat # -loat y);bool o&erator +(double # double y);

    bool o&erator D+(-loat # -loat y);bool o&erator D+(double # double y);

    T*e operators compare t*e operands according to t*e rules o0 t*e EEE +"4 standardB

    0 eit*er operand is =a=- t*e result is -alse 0or all operators e cept ?+ - 0or w*ic* t*e result is true . )orany two operands- # ?+ y always produces t*e same result as ?(# ++ y) . However- w*en one or bot*operands are =a=- t*e - D- +- and D+ operators do not produce t*e same results as t*e logical negation o0t*e opposite operator. )or e ample- i0 eit*er o0 # and y is =a=- t*en # y is -alse - but ?(# D+ y) is true .

    6*en neit*er operand is =a=- t*e operators compare t*e values o0 t*e two 0loating

  • 8/12/2019 Csharp Language Specification v1.2

    172/408

    C# Language Specification v1.2

    T*e result o0 ?+ is -alse i0 bot* # and y are true or i0 bot* # and y are -alse . /t*erwise- t*e result is true .6*en t*e operands are o0 type bool - t*e ?+ operator produces t*e same result as t*e F operator.

    .0.% #numeration comparison operatorsEvery enumeration type implicitly provides t*e 0ollowing prede0ined comparison operatorsB

    bool o&erator ++( # y);bool o&erator ?+( # y);

    bool o&erator ( # y);

    bool o&erator D( # y);

    bool o&erator +( # y);

    bool o&erator D+( # y);

    T*e result o0 evaluating # op y - w*ere # and y are e pressions o0 an enumeration type wit* an underlying type: - and op i


Recommended