c# - the language for the 90s

47
1 C# - the language for the 90s Judith Bishop University of Pretoria, South Africa [email protected] Nigel Horspool University of Victoria, Canada [email protected]

Upload: etta

Post on 09-Jan-2016

36 views

Category:

Documents


3 download

DESCRIPTION

C# - the language for the 90s. Judith Bishop University of Pretoria, South Africa [email protected] Nigel Horspool University of Victoria, Canada [email protected]. Volunteers on a C# course in Africa. Do it in C# Naturally!. Contents. Introduction Basics. The fruits of our labours. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C# - the language for the 90s

1

C# - the language for the 90s

Judith BishopUniversity of Pretoria, South Africa

[email protected]

Nigel HorspoolUniversity of Victoria, Canada

[email protected]

Page 2: C# - the language for the 90s

2

Volunteers on a C# course in Africa

Do it in C# Naturally!

Page 3: C# - the language for the 90s

3

Contents

Introduction Basics

Page 4: C# - the language for the 90s

4

The fruits of our labours

Page 5: C# - the language for the 90s

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.

Page 6: C# - the language for the 90s

6

Goals

general-purpose

software engineering principles

software components for distributed environments.

source code portability

internationalization

embedded systems

Is this Java or C#?

Page 7: C# - the language for the 90s

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

Page 8: C# - the language for the 90s

8

Contents

Introduction Basics

Page 9: C# - the language for the 90s

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

}

}

Page 10: C# - the language for the 90s

10

Some terminology

Program

types

data functions

fields

constantsvariables

constructorsmethodspropertiesoperators

simple

structured

int

classstruct

namespaces

Page 11: C# - the language for the 90s

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

b

c

VMT P

struct T { int b, c; void p {...}}

T a;

Page 12: C# - the language for the 90s

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

Page 13: C# - the language for the 90s

13

The System.DateTime struct

// ConstructorsDateTime (int year, int month, int day);DateTime (int year, int month, int day int hour, int min, int sec);

// Static Propertiesstatic DateTime Now static DateTime Today static DateTime UTCNow // Instance propertiesint Dayint Monthint Yearint Hourint DayOfYear

Plus more

Page 14: C# - the language for the 90s

14

Example - Meetings

for (int hour=8; hour<=18; hour++) {

}

London New York08:00 AM 03:00 AM09:00 AM 04:00 AM10:00 AM 05:00 AM11:00 AM 06:00 AM

meeting = new DateTime (now.Year, now.Month, now.Day, hour, 0, 0);

offsetMeeting = meeting.AddHours(offset);

Console.WriteLine({0:t} {1:t}, meeting, offsetMeeting);

Page 15: C# - the language for the 90s

15

Properties by example

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 { public static void 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); }}

Page 16: C# - the language for the 90s

16

A struct vs a class

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

c d

Page 17: C# - the language for the 90s

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 willcompile, but will compare references

Page 18: C# - the language for the 90s

18

Value and reference semantics Value Types Reference Types

Types int float etc, struct, enum

array, class, interface, delegate

Values Fixed ranges defined by the user or API

Operators predefined defined by user or API

Assignment copies the value copies a reference

Equality must overload ops can overload ops

Created on the stack the heap

Derived from System.ValueType System.Object

Parameters passed by copy passed by reference

Dies when out of scope when garbage collected

Page 19: C# - the language for the 90s

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

Page 20: C# - the language for the 90s

20

Output

Printing is done using the System.Console class

Three approaches:

1. Use concatenationConsole.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 ...

Page 21: C# - the language for the 90s

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}

item number width - default is left,positive means right

format code e.g.f or C or D

Page 22: C# - the language for the 90s

22

Formatting other types

NumberFormatInfo f = new NumberFormatInfo();f.CurrencyDecimalSeparator = ",";f.CurrencyGroupSeparator = " ";f.CurrencySymbol = "€";

Less use of methods through format specifications

double amount = 10000.95;

Console.WriteLine(

String.Format(f, "{0:C}", amount);

€ 10 000,95

Page 23: C# - the language for the 90s

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)Notif (s.Length)

Page 24: C# - the language for the 90s

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)

Page 25: C# - the language for the 90s

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]); }

Page 26: C# - the language for the 90s

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

0123

A SL

Wed

A[1] SL["Wed"]

Page 27: C# - the language for the 90s

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

}

Page 28: C# - the language for the 90s

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

Page 29: C# - the language for the 90s

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?

Page 30: C# - the language for the 90s

30

Demonstration 1 - Public Holidays

The Public Holidays Program

Illustrates– switch on string

– sorted lists

– indexers

– Split

– file handling

GUI specification with Views

Page 31: C# - the language for the 90s

31

Output from the demo

Page 32: C# - the language for the 90s

32

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

virtualabstractV

virtualV

virtualV

override V

OR

override V

Page 33: C# - the language for the 90s

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

virtualF

F

virtualF

new F

1

2

3

Page 34: C# - the language for the 90s

34

Demonstration 2 - StarLords

Illustrates– inheritance

– base constructor calling

– virtual and override

– ref parameters

Page 35: C# - the language for the 90s

35

Program output

Page 36: C# - the language for the 90s

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.

Page 37: C# - the language for the 90s

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

Page 38: C# - the language for the 90s

38

Delegates

Delegates allow references to methods They separate methods from a specific name One step up from interfaces

MM

M

A

B C

F() -- calls M

M

MMM

I

A B C

F() -- calls M

MD

D1(P)D2(Q)D3(R)

F(D1) -- calls P via M

P Q R

A B C

Interfaces Inheritance Delegates

Page 39: C# - the language for the 90s

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.

Page 40: C# - the language for the 90s

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

Page 41: C# - the language for the 90s

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

Page 42: C# - the language for the 90s

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

Page 43: C# - the language for the 90s

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 Alliancehttp://www.msdnaa.net/

Page 44: C# - the language for the 90s

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

Page 45: C# - the language for the 90s

45

.NET offerings

CLISSCLI.NET

ECMA standardisedCommonLanguageInfrastructure

Microsoft Windows’Web serviceFramework

Microsoft’sImplementation ofthe CLI (plus some)= Rotor

Page 46: C# - the language for the 90s

46

Page 47: C# - the language for the 90s

47