1 / 103

C# - the language for the 2000s

C# - the language for the 2000s. Judith Bishop University of Pretoria, South Africa jbishop@cs.up.ac.za Nigel Horspool University of Victoria, Canada nigelh@uvic.ca. Thursday 27 May. www.cs.up.ac.za Choose “courses” Go to bottom of list and choose IRA310

suchi
Télécharger la présentation

C# - the language for the 2000s

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C# - the language for the 2000s Judith Bishop University of Pretoria, South Africa jbishop@cs.up.ac.za Nigel Horspool University of Victoria, Canada nigelh@uvic.ca

  2. Thursday 27 May • www.cs.up.ac.za • Choose “courses” • Go to bottom of list and choose IRA310 • Sign up for exam, and for tutorials

  3. Volunteers on a C# course in Africa Do it in C# Naturally!

  4. Contents • Introduction • Basic C# • GUIs with Views • Advanced OOPS • Networking • Technical considerations

  5. C# Concisely • First year programming text book due September 2003 • Addison Wesley, 2003 • Incorporates Views • Reviewed by Microsoft • Contents on the Views website http://www.cs.up.ac.za /rotor

  6. Microsoft Comments “Many computer books are so heavy that lifting them causes a hernia, yet they have less content than your favorite tabloid. Many academic text books are so boring that they turn your brains to dust, yet they don't teach you anything that is of use in the real world. Not with this book! …” Erik Meijer, Technical Lead, MS Web Data Team

  7. Facts on C# • Designed at Microsoft by Anders Hejlsberg (Delphi, Java Foundation classes). Scott Wiltamuth and Peter Golde • Language of choice for programming in .NET • Standardised by ECMA December 2002 and ISO April 2003   • It is expected there will be future revisions to this standard, primarily to add new functionality.

  8. Goals • general-purpose • software engineering principles • software components for distributed environments. • source code portability • internationalization • embedded systems Is this Java or C#?

  9. Why should I know about C#? • A good language, well supported • Useful for teaching e.g. data structures, compilers, operating systems, distributed systems, first year • Inter-language operability via .NET (Java doesn't) • Multi-platform via Rotor (like Java) • Not tied to an IDE or rapid development (like VB or Delphi) • Efficiency potential (scientific programming) • Base for future development e.g. XEN

  10. Contents • Introduction • Basic C# • GUIs with Views • Advanced OOPS • Networking • Technical considerations

  11. Syntactic niceties • A slightly enhanced Hello World using System; class Welcome { static void Main() { string name = " Peter "; Console.WriteLine("Welcome to C#" + name); Console.WriteLine("It is now " + DateTime.Now); } } The libraries are the language

  12. Program simple int types class struct structured functions data namespaces fields constructors methods properties operators constants variables Some terminology

  13. Structured types - structs • Structs are lightweight - should be used often • Structs can have fields, methods, properties, constructors, operators, events, indexers, implemented interfaces, nesting • Structs cannot have destructors, inheritance, abstract a struct T { int b, c; void p {...} } T a; b c p function

  14. Initialisation • Struct initialisation rules: • instance fields may not be initialised • static fields may be initialised • if there is a constructor, then all fields must be initialised there • if no constructor, values are unspecified struct T { static int a; int b, c; T { b = 4; c = 6; } } a = 0 b = 4 c = 6

  15. The System.DateTime struct // Constructors DateTime (int year, int month, int day); DateTime (int year, int month, int day, int hour, int min, int sec); // Static Properties static DateTime Now static DateTime Today static DateTime UTCNow // Instance properties int Day int Month int Year int Hour int DayOfYear Plus more

  16. Example - Meetings Console.WriteLine("London New York"); for (int hour=8; hour<=11; hour++) { } meeting = new DateTime (now.Year, now.Month, now.Day, hour, 0, 0); offsetMeeting = meeting.AddHours(offset); Console.WriteLine("{0:t} {1:t}", meeting, offsetMeeting); London New York 08:00 AM 03:00 AM 09:00 AM 04:00 AM 10:00 AM 05:00 AM 11:00 AM 06:00 AM

  17. using System; struct City { string name; DateTime meeting; public City(string n, DateTime m) { name = n; meeting = m; } public DateTime Meeting { get {return meeting;} set {meeting = value;} } public string Name { get {return name;} } } class TestTutorial { publicstaticvoid Main() { City conference = new City ("Klagenfurt", new DateTime(2003,8,24)); conference.Meeting = new DateTime(2003,8, tutorial.Meeting.Day-1); Console.WriteLine( "Speaking at " +conference.Name+ " on "+ conference.Meeting); } } Properties by example

  18. struct complex { double re, im; } complex c; must define equality and comparison class complex { double re, im; } complex d; for values, must define equality and comparison A struct vs a class c d

  19. Structured types - classes • Classes are heavyweight • Classes can have fields, methods, properties, constructors, operators, events, indexers, implemented interfaces, nesting • … and destructors, inheritance, abstract a class T { int b, c; void p {...} } T a; b c VMT p function

  20. Equality • public override bool Equals(object d) { •     Pet p = (Pet) d; •     return name==p.name && type==p.type; • } • if (i>1 && p.Equals(list)) { •     Console.WriteLine("Repeated data."); •   } else { • Have to be careful because p==list will compile, but will compare references

  21. Value and reference semantics

  22. Type promotion • The results of a mixed numerical expression are promoted to the type with the greater range. • if either operand is double, the result is double, • otherwise if either operand is long, the result is long, • otherwise the result is int. • For operations on bytes, the result is always converted to an int. • Division applied to integers produces an integer result. So for example we have: 7 / 3 = 2 3 / 4 = 0

  23. Explicit type conversion • (typeid) expression or checked ((typeid) expression) • The expression is evaluated and converted to the type specified, with possible loss of information. • Real numbers are rounded towards zero to make integral values. • If the type cannot hold the resulting value and checking is turned on, an error called an OverflowException occurs. • Placing checked in front of the conversion forces the exception to happen, even if the checking option is off in the compiler. int i = 6; double z; double x = 3.14; double y = 5.003000000008E+15; z = i; // always valid - value is 6.0 i = x; // compiler error - must explicitly convert i = y; // compiler error - must explicitly convert i = (int) x; // valid - value is 3; i = (int) y; // execution error if checked is on, // unspecified value otherwise

  24. in, out and ref parameters • in • pass by value • the default • out • value copied out only (not in as well) • used to return multiple values from a method • ref • pass by reference • changes are made to the actual object • out and ref must be specified by caller and callee void Rearrange(ref City a, ref City b) { DateTime temp = a.MeetingTime; a.MeetingTime = b.MeetingTime; b.MeetingTime = temp.MeetingTime; } Rearrange(ref London, ref NewYork);

  25. Visual Studio I’ve done some overtime today, so the Visual Studio .NET 2003 is available for our students from today on at the download server I told them today. The software is available in the English and German (even Chinese) version.   For those who don’t want to use the Visual Studio, the .NET SDK will be available within the next few days from the download server. http://maniac.stud.uni-karlsruhe.de Andreas Heil Microsoft Student Consultant MAP - Microsoft Academic Program Email : i-aheil@microsoft.com Web: http://www.studentconsultant.org/unikarlsruhe/ Mobile: +49 (0)174 9045832

  26. Output • Printing is done using the System.Console class. Three approaches: • 1. Use concatenation Console.WriteLine(name +" " + descr + " for G" + price); • 2. Use ToString public override string ToString() { return name + " " + descr + " for G" + price; } Baskets grass, woven for G8.5 cont ...

  27. Formatted output • 3. Use a format string, where the justification and field widths of each item can be controlled Console.WriteLine("{0} {1} for G{2,0:f2}" name, descr, price); Baskets grass, woven for G8.50 {N,M:s} format code e.g. f or C or D width - default is left, positive means right item number

  28. Formatting other types • Less use of methods through format specifications double amount = 10000.95; Console.WriteLine( String.Format(f, "{0:C}", amount)); € 10 000,95 • NumberFormatInfo f = new NumberFormatInfo(); • f.CurrencyDecimalSeparator = ","; • f.CurrencyGroupSeparator = " "; • f.CurrencySymbol = "€";

  29. Control structures • C# has the standard C++ or Java control structures, viz: • for • if-else and goto! • while • do-while • switch-case • Conditions must be explicitly converted to bool • The switch has two very nice features: • case on strings • Compulsory break after a case if (s.Length == 0) Not if (s.Length)

  30. Collections - Arrays • Arrays are indexed by number e.g. int [] markCounts = new markCounts[101]; string [] monthNames = new string[13]; DateTime[] myExams = new DateTime[noOfExams]; • C# follows the C/Java tradition of • Once declared, their size is fixed. • The indices are integers and start at zero. • There is a property called Length. • The elements in the array can be any objects. • Bounds are always checked (ArrayOutOfBoundsException)

  31. Array class • Corresponding to the “type” array there is an Array class with useful methods e.g. • Array.BinarySearch(a, v) • Array.Clear(a, first, num) • Array.IndexOf(a, v) • Array.Sort(a) • Example, including Split 24 8 2003 public Date(string s) { string[] elements = s.Split(' '); day = int.Parse(elements[0]); month = Array.IndexOf(monthNames,elements[1]); }

  32. Indexers • All of these have [ ] overloaded, so that they can operate exactly like an array in a program • C#’s rich collections include • Hash tables • Sorted lists • Stacks • Queues • BitArrays • ArrayLists SL A 0 1 2 3 Wed A[1] SL["Wed"]

  33. Example of SortedLists COS110 350 GEOL210 80 ENG100 600 class Enrollments { string code; int size; public Enrollments(string c, int s) { code = c; size = s; } ... other methods here }

  34. … continued • Define a list SortedList year2003 = new SortedList(100); • Put an object in the list using the same notation as for arrays year2003["PHY215"] = new Enrollment("PHY215", 32); • Print out the enrollment for Physics Console.WriteLine("PHY215 has " + (Enrollment)year2003["PHY215"].size + "students"); PHY215 has 32 students

  35. Foreach loop • Designed to loop easily through a collection foreach (type id in collection.Keys) { ... body can refer to id } • Example foreach (string course in year2003.Keys) { Enrollment e = (Enrollment) year2003[course]; Console.WriteLine(e.code + " " + e.size); } • Can’t say foreach (string course in year2003) Why?

  36. Demonstration 1 - Public Holidays • The Public Holidays Program • Illustrates • switch on string • sorted lists • indexers • Split • file handling • GUI specification described later

  37. Output from the demo

  38. Contents • Introduction • Basic C# • GUIs with Views • Advanced OOPS • Networking • Technical considerations

  39. Views – Vendor independent extensible windowing system • SSCLI (and Rotor) has no GUI capability • General move to platform independent GUIs • Views is a Rotor Project to provide GUI specifications and a rendering engine using XML and a toolkit such as Qt or Tcl/TK • Available on http://views.cs.up.ac.za

  40. widget rendering in the OS widget calls in a language Windows GUI Builder Application Add Listeners Handlers Visual Studio C# GUI building today

  41. Example in WinForms show.Click += new EventHandler(ActionPerformed); hide.Click += new EventHandler(ActionPerformed); } public void ActionPerformed(Object src, EventArgs args) { if (src == show) { pic.Show(); } else if (src == hide) { pic.Hide(); } } • Embedded in 115 lines of generated code labelled “do not touch” • Unexplained classes and unused objects here

  42. widget rendering in the OS GUI XML Spec Application Control Engine Handlers Add Listeners A GUI using XML

  43. Example in Views XML Views.Form f = new Views.Form(@"<Form> <vertical> <horizontal> <Button Name=Show/> <Button Name=Hide/> </horizontal> <PictureBox Name=pic Image='C:Jacarandas.jpg' Height=175/> </vertical> </Form>" ); string c; for (;;) { c = f.GetControl(); PictureBox p = (PictureBox) f["pic"]; if (c == null) break; switch (c) { case ”Show" : p.Show(); break; case ”Hide" : p.Hide(); break; } } C# • No pixel positioning • No generated code • Separation of concerns

  44. Demo 2 - ShowHide • Winforms • Make some changes • Views • Make some changes

  45. The Views Notation form: <form>controlGroup</form> controlGroup: <vertical>controlList</vertical> | <horizontal>controlList</horizontal> controlList: { control } textItemList: { <item> text </item> } control: controlGroup | <Button/>| <CheckBox/> | <CheckedListBox> textItemList </CheckedListBox> | <DomainUpDown> textItemList </DomainUpDown> | <GroupBox>radioButtonList</GroupBox> | <Label/>| <ListBox/> | <OpenFileDialog/> | <SaveFileDialog/> | <PictureBox/> | <TextBox/> | <ProgressBar/> | <TrackBar/> radioButtonList: { <RadioButton/> }

  46. A typical control - Button ON • <Button/> *Name=S • Text=S • Image=F • Width=M • Height=M • ForeColor=C • BackColor=C • Creates a push button which is a variable given by the Name S. • The button can be labelled with a Text string or with an Image or both. • The size of the button defaults to something large enough to hold the label, either text or an image or can be set with Width and Height. • Clicking the button causes GetControl to return with the name of the control. <Button Name=onButton Text=‘ON’ /> Compulsory

  47. The Handler methods Essentially five kinds of methods: construct close getControl get put PLUS … direct access Form(string spec,params) The constructor. void CloseGUI( ) Terminates the execution thread string GetControl( ) Waits for the user to perform an action string GetText(string name) Returns the value of the Text attribute int GetValue(string name) Returns the Value attribute from TrackBar, ProgressBar and CheckBox int GetValue(string name, int index) Returns the status of CheckBox at position index void PutText(string name, string s) Displays the string in a TextBox or ListBox control. void PutValue(string name, int v) Sets an integer value associated with a ProgressBar or CheckBox

  48. Views.Form v = new Form (@"<form Text= Lucky> <vertical> <TextBox name =Number Text = '13'/> <Button name = Start/> <ListBox name = Day Width = 270/> </vertical> </form>"); int luckyNumber = int.Parse(v.GetText("Number")); Random r = new Random (luckyNumber); for( ; ; ) { string s = v.GetControl( ); if (s==null) break; switch (s) { case "Start": DateTime luckyDate = new DateTime(DateTime.Now.Year, r.Next(3,12);, r.Next(1,30);); v.PutText("Day", "Your lucky day will be " + luckyDate.DayOfWeek + " " + luckyDate.ToString("M")); break; }}

  49. Multiple controls - arrays in XML? • Arrays of product names and images • Arrays of prices (in the background) double[ ] unitCost = new double[maxNumProducts]; string[ ] item = new string[maxNumProducts]; <Button Name=??? Image=‘Apples.gif’ Width=72 Height=72/>

More Related