session 2

66
T9 .NET Programming for the Business – Spring 2007 Session 2 C# February 6th - 2007

Upload: baina

Post on 06-Jan-2016

36 views

Category:

Documents


0 download

DESCRIPTION

Session 2. C# February 6th - 2007. This week’s info. Exercises will start next week due to the time of day. Use class breaks, get a hold of me after class or email. Project will be given next week. All students who are not enrolled can do so this week. C#. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Session 2

T9 .NET Programming for the Business – Spring 2007

Session 2

C# • February 6th - 2007

Page 2: Session 2

T9 .NET Programming for the Business – Spring 2007

This week’s info

• Exercises will start next week due to the time of day.• Use class breaks, get a hold of me after class or email.• Project will be given next week.• All students who are not enrolled can do so this week.

Page 3: Session 2

T9 .NET Programming for the Business – Spring 2007

C#

• C# is a language created by Anders Hejlsberg to provide a vehicle for writing enterprise applications in .NET.

• C# resembles Java a lot, but provides innovations in type safety, versioning, events and garbage collection.

• C# is an ECMA standard (as opposed to Java). (http://www.ecma-international.org/ and http://en.wikipedia.org/wiki/Ecma )

• The smarts of .NET is not in a particular language, but in the libraries.

• Remember: The role of the compiler is to make life easy, not difficult.

• There is a new standard (C# version 2.0) that is in the 2005 (Whidbey) packages.

• Version 3.0 is coming soon.

Page 4: Session 2

T9 .NET Programming for the Business – Spring 2007

General structure

• C# programs consist of one or more files.

• Each file can contain code from one or more namespaces.

• A namespace can contain types such as classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces.

• There is no order enforced by the system (like there is in e.g. C++).

// A skeleton of a C# program using System;namespace MyNamespace1 { class MyClass1 { } struct MyStruct { } interface IMyInterface { } delegate int MyDelegate(); enum MyEnum { } namespace MyNamespace2 { } class MyClass2 { public static void Main(string[] args) { } }}

Page 5: Session 2

T9 .NET Programming for the Business – Spring 2007

Classes.

• A Class is a definition of an object.• A Class encapsulates a state and behaviour.• Powerful abstraction concept. Models realworld concepts.• Objects are instances of Classes.• Classes in .NET are quite similar to classes in other OO languages.• Classes are Types.

Page 6: Session 2

T9 .NET Programming for the Business – Spring 2007

Class state

• A object defines its state at a given time through the values of the object's member variables.

• The state is modified through the operations (behaviour) provided by the object.

• Model some real life objects...

Page 7: Session 2

T9 .NET Programming for the Business – Spring 2007

A property/state example

Page 8: Session 2

T9 .NET Programming for the Business – Spring 2007

A method example

Page 9: Session 2

T9 .NET Programming for the Business – Spring 2007

UML

• As a profession, we need a language to express designs and ideas.

• Compare with any other profession:

Mathematical:

Page 10: Session 2

T9 .NET Programming for the Business – Spring 2007

Electronics:

Page 11: Session 2

T9 .NET Programming for the Business – Spring 2007

Architecture:

Page 12: Session 2

T9 .NET Programming for the Business – Spring 2007

UML

• There are several methodogies available, but the one most commonly used is Unified Modelling Language, or UML.

• UML was invented by the OMG (Object Management Group).• http://en.wikipedia.org/wiki/Unified_Modeling_Language• Programming language agnostic.• We will be discussing:

– Class diagrams.– Sequence diagrams.– Activity diagrams.

Page 13: Session 2

T9 .NET Programming for the Business – Spring 2007

Class Diagrams

• Class diagrams are the most commonly used UML diagrams.

• A class diagram defines classes and the relationships that hold between them.

• Class diagrams show operations and fields for a given class.

• We will be using class diagrams to introduce some class concepts used in OO in general and in .NET in particular.

Page 14: Session 2

T9 .NET Programming for the Business – Spring 2007

UML Class diagrams: A class

+ToString() : string

-name : string = ""-birthday : Date

Person

The Class name

Properties

Methods

Page 15: Session 2

T9 .NET Programming for the Business – Spring 2007

Inheritance: Human example

FatherMother

Child1 Child2 Child3

Page 16: Session 2

T9 .NET Programming for the Business – Spring 2007

Inheritance: Human example

• Uncontrollable results• More properties or less properties• Can be for the better or for worse• Properties can clash

Page 17: Session 2

T9 .NET Programming for the Business – Spring 2007

Inheritance: Transitive

• Inheritance is a transitive relation.

• Let C be derived from B and B be derived from A. B inherits from A and C inherits from B (and A).

• Derived classes can add elements, and it can override elements, but not remove the elements from the base class.

• ALL types are derived from a common root class, the System.Object class.

• Note that ALL types are objects in C#, not only reference types.

A

B

C

Page 18: Session 2

T9 .NET Programming for the Business – Spring 2007

UML class diagrams: Inheritance

+ToString() : string

-name : string = ""-birthday : Date

Person

+ToString() : string+CalculateWages() : decimal

+hiredOn : Date

Employee

Specialization

Page 19: Session 2

T9 .NET Programming for the Business – Spring 2007

Abstract Classes

• Abstract classes cannot be instantiated directly. They contain abstract methods that must be implemented by derived classes.

+Feeds()

-age : long

Animal

-PulmonaryCapacity : float

Mammal

-gillArea : float

Fish

+Feeds()

Whale

+Feeds()

Human

+Feeds()

Cod

Page 20: Session 2

T9 .NET Programming for the Business – Spring 2007

Classes: Visibility of class members

• Class operations work on the internal state. It is always convenient to hide away the details of implementation to the class' clients.

• To this end, members may be internal, private, protected or public (and sealed in c#).

• Prefix the member by– - for private members– # for protected members– + for public members.

• Use lowercase for member names.• Members may be static or not static (instance).

– Static member names are underlined.

Page 21: Session 2

T9 .NET Programming for the Business – Spring 2007

UML class diagrams: Associations & Aggregations

Order Customer

1

-customer

1

Orderlines

+order1

+lines1..*

• Use unfilled diamond if the target leads a life of its own.

• Use filled diamond if the class pointed to does not contains a life of its own.

Page 22: Session 2

T9 .NET Programming for the Business – Spring 2007

UML Class diagrams: Comments

• You should annotate your diagram by using comments.

• Comments should enhance legibility and aid comprehension.

• Use dashed line if you want to tie the comment to somewhere specific.

Orders

Order lines

1

-lines*

All orders have oneor more lines..

Page 23: Session 2

T9 .NET Programming for the Business – Spring 2007

UML Object diagrams

• Class diagrams deal with the structure of data.

• Object diagrams describe instances of data (snapshots).

• Left: The classes and relationships involving orders and orderlines.

• Right: A order with two order lines created on the 1. january 2003.

date : Date = 1. jan 2003

anOrder : Orders

Quantity : intItem : string

Object1 : Order lines

Quantity : int = 2Item : string = Widget

Object2 : Order lines

Order Order-date : Date

Orders

-Quantity : int-Item : string

Order lines

1

-lines*

All orders have oneor more lines..

Page 24: Session 2

T9 .NET Programming for the Business – Spring 2007

Exercise: Buildings

• Construct a class “building” with basic properties and methods.• Construct at 2 branches “skyscraper” and “mobile home” with

additional properties and methods. This class inherits from “building”

• Construct 2 classes “door” and “window” (with some properties), that have a one-to-many relation to the “mobile home”

Page 25: Session 2

T9 .NET Programming for the Business – Spring 2007

One solution

Page 26: Session 2

T9 .NET Programming for the Business – Spring 2007

Using part

using System;

using System.Collections;

using System.Collections.Generic;

using System.Text;

using Session2_lib; //custom lib.

Page 27: Session 2

T9 .NET Programming for the Business – Spring 2007

Namespace part

• Namespaces are a way to define the classes into one hierarchical structure.

• Has nothing to do with the execution• Strictly for organizing and branding code• You can have as may namespaces as you like.• Namespaces are meant to make coding simpler!• You can NOT use the name “System” as a custom namespace!

• Namespace Customer• Namespace Customer.Address

Page 28: Session 2

T9 .NET Programming for the Business – Spring 2007

Class part

• Classes define a type, of object.

• Classes are the core of C# and object-oriented programming.

• Classes should encapsulate your methods in groups of functionality.

• Classes are declared within a namespace

public class Employee

{

public void DoWork()

{

}

}

Page 29: Session 2

T9 .NET Programming for the Business – Spring 2007

Partial class

public partial class Employee{ public void DoWork() { }}

public partial class Employee{ public void GoToLunch() { }}

Page 30: Session 2

T9 .NET Programming for the Business – Spring 2007

Method(s) part

• A method is a code block containing a series of statements • In C#, every executed instruction is done so in the context of a

method. • Specifying the access level, the return value, the name of the

method, and any method parameters.• Method parameters are surrounded by parentheses, and separated

by commas. • Empty parentheses indicate that the method requires no

parameters. • Methods are declared within a class

Page 31: Session 2

T9 .NET Programming for the Business – Spring 2007

Method

public class Motorcycle

{

public void StartEngine() { }

public void AddGas(int gallons) { }

public int Drive(int miles, int speed) { return 0; }

}

Page 32: Session 2

T9 .NET Programming for the Business – Spring 2007

.NET building blocks

• Programming is like building houses

•The programmer is the architect (or a specific person in the project is given that role)

• C#’s name for building blocks is “assemblies”

•Microsoft has developed a huge amount of “blocks” for you to use (and ease your programming)

Page 33: Session 2

T9 .NET Programming for the Business – Spring 2007

Techniques and skills

Good programming …

Page 34: Session 2

T9 .NET Programming for the Business – Spring 2007

Techniques and skills

BAD programming …

Page 35: Session 2

T9 .NET Programming for the Business – Spring 2007

.NET Assemblies

• The output of the compilation process is an assembly or an executable file.

• Any number of source texts go into building an assembly.• An assembly can contain any number of classes from any number

of namespaces.• Assemblies typically refer to other assemblies.• At runtime, all the assemblies are stored together and deployed.

Page 36: Session 2

T9 .NET Programming for the Business – Spring 2007

Assemblies – Simple structure

Page 37: Session 2

T9 .NET Programming for the Business – Spring 2007

Assemblies – Complex structure

Page 38: Session 2

T9 .NET Programming for the Business – Spring 2007

Namespaces

• Namespaces provide a naming schemes for grouping related types.

• Helps developers focus and browse and reference types.• Convenience as programs and libraries get larger.• Used to resolve naming conflicts.• Types are included in a namespace when it appears within a

namespace block.• Namespaces may be defined in any number of source files.• Types may be referred to by using their full (qualified) name or

implicitly by having using clauses (using unqualified names).

Page 39: Session 2

T9 .NET Programming for the Business – Spring 2007

Assemblies.

• Assemblies are the building blocks of .NET applications.• Assemblies are:

– Reusable– Versionable– Secure– Self describing.

• Assemblies consist of two parts:– Types and resources used to provide a logical unit of

functionality.– Metadata that describes how these elements relate and what

they depend on.• The metadata that describes the assembly is called the assembly

manifest.

Page 40: Session 2

T9 .NET Programming for the Business – Spring 2007

Namespaces and Assemblies

• There is no relationship between namespaces and assemblies.• An assembly can contain types from any number of namespaces.• Classes from the same namespace may be located in different

assemblies.• However, members may be marked internal causing access from

classes in the same assembly.

Page 41: Session 2

T9 .NET Programming for the Business – Spring 2007

To sum it all up – Methods vs classes

StartEngine() Drive() Break() StopEngine()

Class

Page 42: Session 2

T9 .NET Programming for the Business – Spring 2007

To sum it all up – Classes vs assemblies

CarMotionControl LightsControl() DoorManagement()

Assembly

StartEngine() Drive() Break()

Page 43: Session 2

T9 .NET Programming for the Business – Spring 2007

To sum it all up – Assemblies vs Project

Project

Car Assembly Road Assembly Gasoline Assembly

CarMotion Lights Doors

.Exe or Assembly

Page 44: Session 2

T9 .NET Programming for the Business – Spring 2007

Compiling C# programs

• There are several choices, depending on the environment you have chosen to work in.

– Command line: csc HelloWorld.cs.– Use your favourite IDE.

• The IDEs are normally just wrappers around the compiler.• The compiler reads ALL the files and generates ONE assembly

from them. There are no ”object files” and no ”linking phase”.

Page 45: Session 2

T9 .NET Programming for the Business – Spring 2007

Using VS.NET

• Source texts are arranged in projects. • A solution may contain one or more projects.• There are several useful project types. • Lots of code is generated for the user.• Help is always near...

Page 46: Session 2

T9 .NET Programming for the Business – Spring 2007

Short Demo of VS.NET

• Locations of things• Create project• Add project to a solution• Make a reference

Page 47: Session 2

T9 .NET Programming for the Business – Spring 2007

C# Compilation

• Demo. Using the command line compiler.• Using the VS environment• Using Reflector (http://www.aisto.com/roeder/dotnet/) to inspect the

generated assembly.

Page 48: Session 2

T9 .NET Programming for the Business – Spring 2007

.NET Types.

• Everything is derived from System.Object (aka object).• There are two types of type: Reference types (classes) and Value

types (structs, ints, etc).• Instances of reference types live on the heap and are subject to

garbage collection.• Instances of value types (deriving from System.ValueType), on the

other hand, live on the heap and are more lightwieght objects.• There are limitations to value types (no inheritance)

Page 49: Session 2

T9 .NET Programming for the Business – Spring 2007

.NET Data types.

• The .NET environment offers the boolean type and 3 numeric types (integral types, floating point types and decimal type).

• bool values may assume the values true and false.

• Integral types (stored in 2s complement):

TypeSize

(bits)

Range

sbyte 8 -128 to 127

byte 8 0 to 255

Short / System.Int16 16 -32.768 to 32.767

Ushort / System.UInt16

16 0 to 65535

Int / System.Int32 32 -2.147.483.648 to 2.147.483.647

Uint / System.UInt32 32 0 to 4.294.967.295

long / System.Int64 64-9.223.372.036.854.775.808 to

9.223.372.036.854.775.807

ulong / System.UInt64 64 0 to 18.446.744.073.709.551.615

Char / System.Char 16 0 to 65.535

Page 50: Session 2

T9 .NET Programming for the Business – Spring 2007

.NET Floating point types

Type Size (bits) Precision Range

float / System.Float 32 7 digits 1.5 x 10-45 to 3.4 x 1038

double / System.Double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308

decimal / System.Decimal 128 28-29 decimal places +/- 79,228,162,514,264,337,593,543,950,335 and decimal point

Floating point Literals: • Float: 3.14159f • Double: 3.14159265358979323d• Decimal: 7.55m

Page 51: Session 2

T9 .NET Programming for the Business – Spring 2007

Expression Operators

Category Operator(s)  Associativity

Primary (x)  x.y  f(x)  a[x]  x++  x--  new  typeof  sizeof  checked  unchecked left

Unary +  -  !  ~  ++x  --x  (T)x left

Multiplicative *  /  % left

Additive +  - left

Relational <  >  <=  >=  is left

Equality ==  != right

Logical AND & left

Logical XOR ^ left

Logical OR | left

Conditional AND && left

Conditional OR || left

Conditional ?: right

Assignment =  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |= right

Page 52: Session 2

T9 .NET Programming for the Business – Spring 2007

String Type

• Strings (string, System.String) are sequences of unicode characters.

• Strings are immutable.• Strings offer a rich set of operations.• String literals:

– string s = "Hello World";– string s = @"c:\filename.txt";– string s = "c:\\filename.txt";

Page 53: Session 2

T9 .NET Programming for the Business – Spring 2007

The Bool type

• Boolean types may have one of two values: true and false.• Operators include &&, ||, !, ^, is• Evaluation is "Short Circuit”.

// remove old accounts without balanceif (account != null && account.Balance == 0 && (DateTime.Now - account.LastEntry) > TimeSpan.FromDays(100)){ accounts.Remove(account);}

if (account is CorporateAccount){ ...}

if ( (1 == 0) && foobar() ) { // do something }

Page 54: Session 2

T9 .NET Programming for the Business – Spring 2007

The DateTime / Timespan types.

• DateTime values represent points in time (year/month/day/ hour/min/sec/millisec).

• Relational operators work as expected.• Rich conversions to and from strings.• Timespans are values indicating durations in days, hours, minutes,

seconds and milliseconds.

Page 55: Session 2

T9 .NET Programming for the Business – Spring 2007

Array types.

• Array types in C# resemble array types in Java, but not in C++.• An array is an indexed collection of objects, all of the same type.• Remember, arrays are objects too.• Syntax is

– MyType [] myArrayVar = {…}• The size is NOT given at declaration time.• Arrays may have any rank (i.e. number of dimensions)

decimal[] amountsDue = new decimal[10];foreach (decimal amount in amountsDue){ if (amount > 100000) { }}

Page 56: Session 2

T9 .NET Programming for the Business – Spring 2007

Variables

• Variables are locations in storage of a given type.• Each variable lives in a given scope. Refering to a variable outside

its scope causes a compilation error.• Explicit assignment is possible when declaring the variable.

– If the variable is a local variable, there is no default value.– If the variable is a member variable, default values apply.

Page 57: Session 2

T9 .NET Programming for the Business – Spring 2007

Exampleforeach (int integer in integers)

{

string returnString ="";

returnString += integer.ToString();

}

string anotherString = returnString;

string returnString ="";

foreach (int integer in integers)

{

returnString += integer.ToString();

}

string anotherString = returnString;

Page 58: Session 2

T9 .NET Programming for the Business – Spring 2007

C# statements

• C# supports all the statement types you are used to (and then a few new ones).

• Statements end with ;• There are (broadly speaking):

– Conditional branching statements.– Iteration statements.– Unconditional branching statements.– Assignment statements.

Page 59: Session 2

T9 .NET Programming for the Business – Spring 2007

Conditional statements: If

• Optional else and else if parts.• The condition is a boolean

expression. No implicit typecasting is done.

if (i > 10){ i = 0;}else{ i += 1;}

Page 60: Session 2

T9 .NET Programming for the Business – Spring 2007

Conditional Statements: Switch

• Switch statements are an alternative to nested if statements.

• Switch statements allow selecting from a number of different values.

• Optional default part.

• It is an error to fall through one case into the next.

switch (i + 6){ case 1: { f(2); } break;

case 2: { f(5); } break;

default: break;}

Page 61: Session 2

T9 .NET Programming for the Business – Spring 2007

Iteration Statements

• while, do ... while, for, foreach, break, continue• while (bool-expression) statement.• do statement while (bool-expression)

int i;bool found = false;while (i < 10){ if (myObject.matches(i)) { found = true; break; } i += 1;}

do{ i += 1;} while (i < 10);

Page 62: Session 2

T9 .NET Programming for the Business – Spring 2007

Iteration Statement: for

• The for loop allows several operations: Initialization, test and modification.

• Notice the fact that the initia-lization may be used to declare a variable in the scope of the for statement.

for (int i = 0; i <= 10; i++){}

// Infinite loopfor(;;){ if (something) continue; if (something_else) break;}

Page 63: Session 2

T9 .NET Programming for the Business – Spring 2007

Iteration Statement: foreach

• The foreach statement is usable for all types that implement the IEnumerable interface.

using System.Collections;

ArrayList ar = new ArrayList();ar.Add("Hello");ar.Add("World");

foreach (string s in ar){ System.Console.WriteLine(s);}

Hashtable ht = new Hashtable();ht["one"] = 1;ht["two"] = 2;

foreach (string s in ht.Keys){ System.Console.WriteLine("{0}->{1}", s,ht[s]);}

Page 64: Session 2

T9 .NET Programming for the Business – Spring 2007

Iteration Statements: break continue

• break– Causes execution to leave the innermost loop in which the

break statement is contained.• continue

– Causes execution to be immediately transferred to the start of the loop body for execution.

• Using any of these outside a loop produces a compilation error.

Page 65: Session 2

T9 .NET Programming for the Business – Spring 2007

Assignment statements

• Assignments assign values to variables.• Syntax:

– myVar = expression;

• Derived syntaxes exist for the cases where the variable is used in the expression:

– myVar += 5;– myBool ^= true

Page 66: Session 2

T9 .NET Programming for the Business – Spring 2007

Classes revisited

• Classes are optionally inherited from other classes.• Everything is derived from Object.• Methods marked with virtual may be overridden in derived

classes.• Classes may be abstract containing one or more abstract

methods.• Classes may be sealed.• Classes may implement one or more interfaces.• Methods may be static or instance methods.• Methods may be overloaded.• Constructors.