470 likes | 552 Views
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.
E N D
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
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.
Goals • general-purpose • software engineering principles • software components for distributed environments. • source code portability • internationalization • embedded systems Is this Java or C#?
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
Contents • Introduction • Basics
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); } }
Program simple int types class struct structured functions data namespaces fields constructors methods properties operators constants variables Some terminology
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
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
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
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
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
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
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
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);
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 ...
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
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 = "€";
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)
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)
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]); }
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"]
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 }
… 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
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?
Demonstration 1 - Public Holidays • The Public Holidays Program • Illustrates • switch on string • sorted lists • indexers • Split • file handling • GUI specification with Views
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
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
Demonstration 2 - StarLords • Illustrates • inheritance • base constructor calling • virtual and override • ref parameters
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.
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
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
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.
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
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
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
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/
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
.NET offerings ECMA standardised Common Language Infrastructure Microsoft’s Implementation of the CLI (plus some) = Rotor Microsoft Windows’ Web service Framework SSCLI .NET CLI