Top Banner
Building Applica-ons in C# Mike Teodorescu ’11 Microso9
53

Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Dec 30, 2018

Download

Documents

doantruc
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

BuildingApplica-onsinC#

MikeTeodorescu’11Microso9

Page 2: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Hello

•  CS50TF‘09,‘10•  CSconcentratorclassof2011•  WorkedonWindowsHomeandSmallBusinessServer2011asaninterninRedmond,WA

•  NowengineerintheApplica-onVirtualiza-onteamattheMicroso9NewEnglandResearchandDevelopmentCenter(NERD)

Page 3: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Microso9NERD

•  Teams:– Applica-onVirtualiza-on– Microso9Research–  SharepointWorkspace2010– Office365– Microso9Lync–  Interac-veEntertainmentBusiness– Microso9Adver-sing– Microso9‐NovellInteroperabilityLab

•  Address:1MemorialDriveinCambridge•  h\p://microso9cambridge.com

Page 4: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

•  Allowsapplica-onstoruninseparatevirtualenvironments,elimina-ngconflictswithotherapplica-onsorwithdifferentversionsofthesameapplica-on.

•  Previouslyincompa-bleappscanberunsimultaneously

•  Fullyfunc-onalWindowsappsarestreamedondemandtousers’desktops

•  Weworkonverylargescalesystems•  Moreath\p://microso9cambridge.com/Teams/Applica-onVirtualiza-on/tabid/83/Default.aspx

Page 5: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 6: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

IntrotoC#•  Object‐orientedprogramminglanguage•  Type‐safetyguaranteed– cannotstoredataofonetypeinaloca-oncorrespondingtoadifferenttype

– cannothaveunini-alizedvariables•  Garbagecollec-on–automa-cmemorymanagement(noneedtoworryaboutfreeingmemoryyouallocated)

•  Built‐indatastructuresthathandletheirownsizing•  Excep-onhandlingallowsdetec-onandrecoveryfromerrorsduringexecu-onofyourcode

Page 7: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

IntrotoC#(2)•  CodeissandboxedintoaVirtualExecu-onSystemwhichensuressafecodeexecu-onandmemorymanagement

•  C#comeswiththe.NETFrameworkClassLibrary,whichmeansitispackedwithlibrariesthatsimplifymanycommontasksthatyouwouldotherwisehavetocode:–  XMLandstringparsing– webprogramming–  datastructures–  scalablenetworksandserverprogramming–  databasemanagement– GUIprogramming,andothers…

•  Parallelprogrammingmadeeasy(ParallelCompu-ngPla=orm–takescareofthelowerlevelcodingforyou)

Page 8: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

IntrotoC#(3)•  Standardtypesarebuilt‐in•  YoucancreateyourcustomtypesthroughOO

•  C#enablescomponent‐orientedprogramming,whichmeansyoucancreateself‐containedunitsoffunc-onalitythatcancommunicate

•  Yourcodeisalivingecosystem–extensibleandeasytomaintain.

•  Thegoalistoallowyoutospendmore-meontheconceptsandlessonlower‐leveldetails.Itenablesyoutothinkmoreaboutyoursolu-onandtheabstractmodelbehindit.

Page 9: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

DevelopmentEnvironment•  SomebenefitsofusingVisualStudio2010:– Mul-tudeoflanguagesyoucanuse(VisualC#,VisualC++,VB)–the.NETlanguagesalluseacommontypesystem

– Auto‐Complete– Auto‐formapng

– Cross‐plaqormdevelopment– Mul-tudeofcodetemplatesandstubs– Debuggingmadeeasy

–  IntegratedGUIdesigntools–  IntegratedTes-ngtools

Page 10: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

DevelopmentEnvironment(2)•  Sourcecontrol•  Candevelopanythingfromaconsoleappto:–  clouddevelopment,– GUIapps,– webservers,– webapps,–  tes-ngframeworks,– Windows8apps,– WindowsPhoneapps,– Officeadd‐ins,–  toverylargecollabora-veprojects

Page 11: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 12: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Basics

•  Usingstatement•  Referencing•  Namespace‐seehierarchydenotedusing.–  System–  System.Collec-ons–  System.Collec-ons.Generic

•  Class•  Method•  DEMO

Page 13: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 14: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

ObjectOriented

•  Programmingwithclassesmakesformoreextensiblecode(allowingyouforinstancetodefineyourowntypesandcontrolwhatisaccessible

•  Encapsula-on=hideinternalimplementa-ondetailsofaclass(datahiding,thisisprivate)

•  Abstrac-on=publicinterfaceofaclass,theexternaldetailssuchasac-onsthattheclasscanperform(thisisvisibletoeveryone)

Page 15: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

OO(2)

•  Tocreateanobjectofthetypedefinedinaclass,weneedtoinstan-atethatclass.Tobeabletodoso,theclassmustdefineaconstructor:

myClassfoo=newmyClass();•  Constructorscanbeoverloaded–wecancreateseveralmethodswiththesamenamebutdifferentparameters(thusdifferentsignatures)

Page 16: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

OO(3)

•  Modifiers– private–onlyaccessibleinsidetheclass– public–accessiblebyeveryone– sta-c–dataandmethodsthatcanbeaccessedwithoutcrea-nganinstanceoftheclass

– const–forconstants•  Scope:Namespaces,classes,andmethods

Page 17: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

OO(4)

•  Amethodinaclassisafunc-on–it’sbasicallyanac-onthatanobjectdefinedbytheclasscantake

•  Apropertyinaclassisadataitemwhosereadandwriteaccessisdefinedbyyou(requireagetandaset:

public class Student {

//privately set private string _name; public string Name { //public read get return _name; }

}

Page 18: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

OO(5)

•  Inheritance:aclasscaninheritallcharacteris-csandac-onsfromaparentclass

•  Thechildclasscanhaveitsownprivatedata,addedmethodsthatarenotfoundintheparent,orredefinethebehaviorofinheritedmethods

•  Aclasscanonlyinheritfromoneparent

•  DEMO

Page 19: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 20: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Arrays// Single-dimensional int[] array1 = new int[10];

// Declare and set values for a single-dimensional array int[] array2 = new int[] { 1, 2, 3 };

// OR int[] array2 = { 1, 2, 3 };

// Declare a 2D array int[,] twoDimensionalArray1 = new int[2,1];

// Declare and set 2D array int[,] twoDimensionalArray2 = { { 1 }, { 2 } };

Page 21: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

ArrayIni-aliza-onandIndexing

Class Program

{ static void Main()

{ int[] array = new int[10];

for(int i=0; i < array.Length; i++)

array[i] = i*i; }

}

Page 22: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

ArrayClassSta-cMethods

•  void Clear(array, index, len) – setsarangetonull,orzero,orfalse,dependingontheelementtypeofthearray

•  int BinarySearch(array, value, comparer) –returnseithertheindexofthesearchedvalue,oranega-venumberifthevalueisnotfound

•  void ForEach(action) – performs the action on each element of the array

Page 23: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

GenericCollec-ons

•  Workwithbuilt‐inanddeveloper‐definedtypes(thus“Generic”–alltypesyoudefineinheritfromobject)

•  Immediatebenefits:typesafety•  AredefinedintheSystem.Collec-ons.Genericnamespace

•  Providealargevariety,readyforyouruse:Lists,Dic-onaries,SortedLists,LinkedLists,SortedDic-onaries,Sets,Stacks,Queues,andmore…

Page 24: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

List<T>

•  Unlikeanarray,aListdynamicallysizesasneeded

•  Ifyouneedsequen-alaccesstoelements,useaLinkedList<T>

•  Listssupportaddinganelementorarangeofelementsattheendofthelist(AddandAddRange)

Page 25: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Dic-onary<Tkey,Tvalue>

•  Usefulmethods:– ContainsKey,– ContainsValue,– Remove(removesthevalueassociatedwiththepassedkey)

– Clear– Add(willthrowanexcep-onifkeyalreadyexistsmustcheckifthedictcontainsthekeyyoutrytoadd)

– TryGetValue(getsthevalueassociatedwiththekeyyou’repassingtoit)

Page 26: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

MoreAdvanced

•  Forfuturedevelopmentinterests:

Thread‐safecollec-ons(ConcurrentDic-onary)

ReadilyusableinSystem.Threading.Tasks.Parallel

(generallythetaskparallellibrarymakesmul-threadedprogrammingprojectssimplertodevelopbytakingcareofsomelowerleveldetails)

Page 27: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

ControlFlow

•  If/else,switch,for,while,dowhile,arethesame

•  FOREACHstatement–neatsincewehavedatastructuresthathaveanenumeratordefinedonthem(suchaslists,dicts,etc)foreach(varkeyvalueindic-onary){…}DEMOfordatastructuresbundledwithStringsdemo

Page 28: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 29: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

StringsandREGEX

•  Built‐intypescharandstring•  EmptystringisString.Emptyor“”

•  Unassignedstringisanull•  Caneasilycreatestringsfromotherobjectsbycalling.ToString()

•  String.Compare(string,string)

•  String.Concat(string,string)•  String.Split(tokenChar)

Page 30: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

REGEX(1)•  Regularexpressionsenableyoutoperformpa\ernmatching

•  RequireusingSystem.Text.RegularExpression

•  Steps:– Defineapa\ernyouwishtomatch(thisisoftypestring)

–  Regexexpression=newRegex(pa\ern);–  expression.IsMatch(stringYouWishToMatch);

OR– MatchCollec-onlist=expression.Matches(stringYouWishToMatch);

(thisisthesetofallmatchesbyapplyingtheregexrepeatedly)

Page 31: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

REGEX(2)•  Pa\erns:

?matchesprecedingelement0or1+matchesprecedingelement1ormore-mes*Matchesprecedingelement0ormore\dmatchesdecimaldigit(equivalentto[0‐9])\wmatchesanalphanumericchar(equivto[a‐zA‐Z_0‐9]{p}matchesprecedingelementexactlyp-mes{p,q}matchesprecedingelementatleastpbutlessthanq-mes.matchesanycharacterexcept\n[]matchesthecharacterwithinthebrackets[^]NOT(e.g,[^0‐9]matcheseverythingnot0thru9)\smatchesaspace

Page 32: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

REGEX(3)•  Groups:youcandesignategroupswithinyourpa\ernusing()

•  Examplepa\erns:

[0‐9]*

\d{3}\w+

([a‐zA‐Z^0‐9]){3,5}(\d*(\w+))

(\d*(\w+)?)+

Page 33: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

FILEI/O

•  CoveredinStringsREGEXDEMO:– Pathbuilder– Readingfromastream– Wri-ngtoastream– Alsofeatured:star-ngachildprocessandclosingthatprocess

Page 34: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 35: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

XMLandLINQ•  Thissec-onwillshowyouhoweasyitistocreateanXMLparserwithjustafewlinesofcode

•  LINQisthequeryingmechanism(canbeusedforalsofordatabases)

•  Wewillneed:– usingSystem.Xml.Linq

– usingSystem.Xml– usingSystem.Collec-ons.Generic

Page 36: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

XMLExamples•  AnXMLelementcorrespondstotheXElementtype:

<courses> <course Title = “CS50” Location = /> <course Title = “CS121” Location =

“Maxwell Dworkin” /> … </courses>

•  Herecourseisanelement,TitleandLoca-onarea\ributes.WecanstorethemusingtheXElementtype;moreoverwecannavigatea\ributesstoringthemusingtypeXA\ribute.

Page 37: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

XMLExamples<students> <student> <name>Barney</name> <class>2013</class> <house>Currier</house> </student> … </students>

<!--Here we just have a simple key-value pair arrangement and no attributes(value of name=Barney for instance)-->

Page 38: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

SepngXMLelementsXElement xmlDocument =

new XElement(“students”, new XElement(“student”, new XElement(“name”), new XElement(“class”), new XElement(“house”) ) );

•  Nowwehavetosetthevaluesoftheelementswejustcreated: XElement student=xmlDocument.Element(“student”); student.SetElementValue(“name”, “Mike”); //you can see that an XElement stores a //key-value pair – great for storing in a dict

Page 39: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

QueryingXML•  YouneedtofirstsettherootelementoftheXML:Root=XElement.Load(“C:\Foo\bar.xml”);

•  Toaccessallelementsundertherootnode:Root.Elements()

•  Topickthevalueofthefirstelement:Root.Elements().First().FirstA\ribute.Value

Page 40: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

QueryingXML

•  LINQqueryisverysimilartotheSQLqueryyou’refamiliarwith:

FROMelementinRoot.Elements()

SELECTelement

WHERE(…)

No-cethattheFROMactslikeaforeach

Page 41: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

VS2010andXMLsinProjects

•  ItisnotsufficienttoaddtheXMLfiletoyourprojectsolu-on

•  YoumustalsosetintheXMLfile’sProper-estabthe“CopytoOutputDirectory”to“CopyAlways”

•  ThisdoesnotapplyifyourXMLisfromaURL(thenyoudon’tincludeacopyofit,youjustpasstheURLpathtotheLoadmethod).

Page 42: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

TOC1.  IntrotoC#2.  HelloWorld3.  Object‐Orientedconcepts4.  Collec-ons5.  ControlFlow6.  FileI/O7.  StringsandREGEX8.  XMLandLINQQueries9.  Excep-onHandling10. Debugging

Page 43: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(1)

•  Excep-onsserveasameanstoreportfailures,classify,andhandlethem

•  Excep-onsencapsulatealltheinforma-onaboutanerrorinasingleclass‐touseexcep-onsaddausingstatementforusingSystem.Excep-on;

•  Allexcep-onsderivefromtheSystem.Excep-onclass

Page 44: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(2)

•  TheSystem.Excep-onclassprovidesseveralusefulproper-esfordebugging:– Message– StackTrace– HelpLink(op-onalURL)– Data(thisisadic-onary)–  InnerExcep-on(ifanexcep-oniswrappedintoadifferenttypeofexcep-on)

•  Howto“throw”anexcep-on:thrownewSystem.Excep-on();

Page 45: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(3)

•  Standardexcep-ontypes:– ArgumentExcep-on– ArgumentNullExcep-on– DivideByZeroExcep-on– NullReferenceExcep-on–  InvalidOpera-onExcep-on–  IndexOutOfRangeExcep-on– OutOfMemoryExcep-on– StackOverFlowExcep-on– SystemExcep-on

Page 46: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(4)–HandlingLogic•  Try‐Catchblock:youexecutecodeintheTryblockwhichmaythrowanexcep-onofaspecifictypewhichyouthenhandleinthecatchblock:try { int foo = 3/0;

} catch(DivideByZeroException e) { Console.Writeline(“Why did you divide by

zero?”); }

Page 47: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(5)–HandlingLogic•  Try‐Catchblock:youmayhavemul-plecatchblocksfordifferenttypesofexcep-onssuchthatdependingontheexcep-onyouexecuteadifferentblockofcode.

•  Example:catch(SystemException e1) { …} catch(ArgumentException e2) {…} catch(InvalidOperationException e3) {…}

Page 48: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(6)–HandlingLogic

•  Catchblockscanswallowerrors–ifyoujustloganerrormessageinyourcatchblockanddonothandletherootcauseoftheerror,thenyouwillfallintothebaddesignprac-cecalled“swallowinganexcep-on”.

•  Ifyourapplica-onthrowsanexcep-onthatisunhandledbyacatchblockwillresultinanapplica-oncrash.

Page 49: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Excep-ons(7)–HandlingLogic

•  Try‐Finally–thefinallyblockofcodeexecutesregardlessofwhetherornotanexcep-onwasthrowninthetryblock;thefinallyblockexecutesimmediatelya9erthetryblock

•  Try‐Catch‐Finally‐mayhavemul-plecatchblocks,asbefore,butalwaysasinglefinallyblock.

•  DEMO

Page 50: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

MoreAdvanced

•  IFyouenterasitua-oninwhichitisunsafetocon-nue(securityrisksforexample,memorycorrup-on,etc.),insteadofusinganexcep-onuseSystem.Environment.FailFast.

•  FailFastimmediatelyterminatestheapplica-on

•  Suchtermina-onsareshownintheeventlogfortheapplica-on(intheWindowseventlog)

Page 51: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

1.  IntrotoC#2.  BasicSyntax3.  HelloWorld4.  Object‐Orientedconcepts5.  Datastructures6.  ControlFlow7.  FileI/O8.  REGEX9.  Excep-onHandling10. Debugging[DEMO]

Page 52: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Morereferences

•  h\p://msdn.microso9.com•  Alwaysgoodtouse:F12allowsyoutotraveltothedefini-onofatypethatbelongstoareferencedlibrary

Page 53: Building Applicaons in C#cdn.cs50.net/2011/fall/seminars/C_sharp/C_sharp.pdf · • Allows applicaons to run in separate virtual environments, eliminang conflicts with other applicaons

Thanks!