1 / 47

C# - the language for the 90s

C# - the language for the 90s. Judith Bishop University of Pretoria, South Africa jbishop@cs.up.ac.za Nigel Horspool University of Victoria, Canada nigelh@cs.uvic.ca. Volunteers on a C# course in Africa. Do it in C# Naturally!. Contents. Introduction Basics. The fruits of our labours.

etta
Download Presentation

C# - the language for the 90s

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 90s Judith Bishop University of Pretoria, South Africa jbishop@cs.up.ac.za Nigel Horspool University of Victoria, Canada nigelh@cs.uvic.ca

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

  3. Contents • Introduction • Basics

  4. The fruits of our labours

  5. 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.

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

  7. 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

  8. Contents • Introduction • Basics

  9. Syntactic niceties using System; class Welcome { public static void Main() { string name = " Peter "; Console.WriteLine("Welcome to C#" + name); Console.WriteLine( "It is now " + DateTime.Now); } }

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

  11. 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 struct T { int b, c; void p {...} } T a; b c VMT P

  12. 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

  13. 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

  14. Example - Meetings for (int hour=8; hour<=18; 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

  15. 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

  16. 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

  17. 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("Oops - repeated data."); •   } else { • Have to be careful because p==list will • compile, but will compare references

  18. Value and reference semantics

  19. 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);

  20. 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 ...

  21. 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

  22. 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 = "€";

  23. Control structures • C# has the standard C++ or Java control structures, viz: • for-else • 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)

  24. 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)

  25. 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 public Date (string s) { string[] elements = s.Split(' '); day = int.Parse(elements[0]); month = Array.IndexOf(monthNames,elements[1]); }

  26. 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"]

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

  28. … 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

  29. 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?

  30. Demonstration 1 - Public Holidays • The Public Holidays Program • Illustrates • switch on string • sorted lists • indexers • Split • file handling • GUI specification with Views

  31. Output from the demo

  32. override V Inheritance - virtual functions • overridden • base class specifies virtual, and derived class may supply another version using override • overridden abstract • base class specifies virtual abstract, and derived class must supply another version using override virtual V OR virtual V override V virtual abstract V

  33. Virtual functions cont. • hidden • base class supplies a virtual function of the same name as an existing derived class function. Override is not assumed. Derived class should be recompiled with function specified as new, to make the separation explicit. F 1 2 3 virtual F F virtual F new F

  34. Demonstration 2 - StarLords • Illustrates • inheritance • base constructor calling • virtual and override • ref parameters

  35. Program output

  36. Operator overloading • DateTime struct public static DateTime operator +                 (DateTime d, TimeSpan t); public static TimeSpan operator -                 (DateTime d1, DateTime d2); birth + 18 Now - marriage • Not allowed for new ( ) || && = • implicit can be used to make casting automatic public static implicit operator CheckBox(GenObject RHS) { return (CheckBox)RHS.Control; } • Indexer [ ] is not overloaded, but defined like a property with get and set.

  37. Serialisation • Persistence of objects on the net or on disks or a server • All classes marked as [Serializable] can have their objects send out with writeObject and retrieved with readObject. • C# serialization is special in that objects can be serialized in binary or in XML using Serialize and Deserialize • The XML serialising is done via SOAP SoapFormatter swrite = new SoapFormatter (); Swrite.Serialize(output,st); SoapFormatter sread = new SoapFormatter (); Fromdisk = (theType) sread.Deserialize(input); Where output and input are the same file

  38. D1(P) D2(Q) D3(R) F(D1) -- calls P via M F() -- calls M I D M M C A B A C B P Q R M M M Delegates • Delegates allow references to methods • They separate methods from a specific name • One step up from interfaces F() -- calls M A M B C M M Delegates Interfaces Inheritance

  39. Events • Events manage external signals • Each event is connected to a delegate • Classes can register a matching callback method with an event using += and deregister using -= • When the event fires, all registered objects will have their methods fired. • Once the event and delegate are set up (as they are in Windows Forms), the programmer only has to supply the callback methods.

  40. Other C# basic goodies • Enumerations - System.Enum • Param modifier allows variable number of parameters • Five kinds of method access modifiers • public - any object or subclass • private - only the class that defined the method - default • protected - only the class that defined it and its subclasses • internal - for an assembly (this is the Java protected form) • protected internal - as it says • Namespaces for creating a class structure • Remoting, Drawing, Forms, XML, Web • Assemblies for archiving compiled classes, metadata, images etc

  41. Generics • Part of the Rotor Gyro download • Defined in the OOPLSA paper by Kennedy and Syme • Better approach than dynamic polymorphism (based on object supertype) - safety, expressivity, clarity, efficiency Stack s = new Stack(); s.Push((int)s.Pop()+(int)s.Pop()); Stack <int> s = new Stack <int> (); s.Push(s.Pop()+s.Pop()); • Extension to the CLR giving exact runtime types, dynamic linking, and shared code

  42. The bad news • Visual C# requirements • 96Mb workstation, 192Mb server • 600Mb on system drive, 1.5GB installation drive • Visual Studio .Net Professional • On Windows XP Professionsal 160Mb • 3.5Gb on installation drive including 500Mb on system drive • Installation can take 4 hours • Java 1.4 and TextPad • Maximum 48M • 70Mb on disk drive • But C# as a command line compiler is of reasonable size

  43. Where to get C# • ECMA specs: http://msdn.microsoft.com/net/ecma • Microsoft commercial C# and CLR SDK http://msdn.microsoft.com/downloads • Shared source info (Rotor) – for non-Windows platforms http://www.microsoft.com/sharedsource • Microsoft Academic Alliance http://www.msdnaa.net/

  44. Further Reading • Bishop Judith and Horspool Nigel, “C# Concisely”, Addison Wesley, due out July 2003 • Peter Drayton, Ben Albahari, Ted Neward, C# in a Nutshell, O’Reilly, March 2002 • Troelsen, Andrew “C# and the .NET platform” A! press 2001 • Visual Studio help files • DevHood tutorials -- see www.devhood.com • http://www.cs.up.ac.za/rotor -- for the Views project

  45. .NET offerings ECMA standardised Common Language Infrastructure Microsoft’s Implementation of the CLI (plus some) = Rotor Microsoft Windows’ Web service Framework SSCLI .NET CLI

More Related