spring 2007noea: computer science programme 1 c# - introduction language fundamentals: data types...

40
Spring 2007 NOEA: Computer Science Pr ogramme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection Arrays

Upload: stewart-fox

Post on 30-Dec-2015

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

1

C# - Introduction

Language Fundamentals:

Data Types

string

Objects and Classes

Methods

Iteration and Selection

Arrays

Page 2: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

2

C#

• All program logic must be embedded in (typically) a class. Like Java.

• Every executable program must contain a Main-method. The Main-method is the starting point of the application.

• The Main-method has several overloads:– static int Main(string[] args), static void Main(string[] args),

static void Main() or static int Main()

• C# is case-sensitive

• C# supports operator and method overloading

• No multiple enhiritance (only interfaces – as in Java)

• All classes inherit object – as in Java

• Garbage-collection

Page 3: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

3

A class

public class Book{

private string title;private string author;public Book(string t, string a) //Constructor{ title= t; author= a;}public override string ToString(){ return (title+" "+author);}

}

Page 4: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

4

Driver Program (Main)

public class BookMain{ public static void Main() {

Book b1= new Book("C#","Troelsen");Book b2= new Book("Java","Kölling");System.Console.WriteLine(b1.ToString());System.Console.WriteLine(b2);

}}

Page 5: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

5

C#- data types

Keyword Description Special format for literals

bool Boolean true false

char 16 bit Unicode character 'A' '\x0041' '\u0041'

sbyte 8 bit signed integer none

byte 8 bit unsigned integer none

short 16 bit signed integer none

ushort 16 bit unsigned integer none

int 32 bit signed integer none

uint 32 bit unsigned integer U suffix

long 64 bit signed integer L or l suffix

ulong 64 bit unsigned integer U/u and L/l suffix

float 32 bit floating point F or f suffix

double 64 bit floating point no suffix

decimal 128 bit high precision M or m suffix

string character sequence "hello", @"C:\dir\file.txt"

Page 6: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

6

C#- the string data type

• string is an alias for System.String – so string is a class

• Many useful properties and methods are offered by string:– Length (property)– Concat()– CompareTo()– Etc.

Page 7: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

7

Exercise

• Architecture – Exercise:

Arkitektur.htm

Page 8: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

8

C#- using types in C#

• Declaration before use (compiler checked)

• Initialisation before use (compiler checked)

public class App{ public static void Main() { int width, height; width = 2; height = 4;

int area = width * height;

int x; int y = x * 2; ... }}

declarations

declaration + initialization

error, x is not initialised

Page 9: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

9

Arithmetics I

• C# offers the usual arithmetic operations: +, -, * , / and % (modulus)

• +, - and * are defined as usual• / is overloaded:

– If the operand are integers, the integer division is applied:

• 23 / 4 gives 5– If one of the operands is a floating point, the result also

is a floating point:• 23.0 / 4 gives 5.75

– typecasting may be necessary

Page 10: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

10

Arithmetics II

• The modulus operator yields the remainder with integer division:– 23 % 4 gives 3, because 23 divide by 4 yields the quotient 5 and

the remainder 3

• The usual rules of operator precedence are valid in C#:– 2 + 3 * 4 = 2 + (3 * 4) = 14

– (2+3) * 4 = 20

Page 11: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

11

Arithmetics and Data Types

• In C# the result of an arithmetic operation has the “larger” type of the two operands:– int + long yields a long– float + double yields a double– byte + float yields a float– etc.

• It is always possible to assign a variable of a “larger” type a value of a “smaller” type– int x = 23;– long y = x;

Page 12: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

12

An Example

using System;

public class Arithmetic {

public static void Main() {

int a = 1;

int b = 3;

float x = 2.0;

Console.WriteLine(”a+b equals ” + (a+b));

Console.WriteLine(”and not ” + a + b);

Console.WriteLine(”a+x equals ” + (a+x));

}

}

What’s wrong here?

Page 13: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

13

Type Casting

• One can change the type of an expression using explicit casting: int count = 24; int total = 100; float average = (float) total / count ;

• Syntax: (data type) variable name

• Type casting has higher precedence than arithmetic operations

Page 14: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

14

C#- type conversion

• Some type conversions are done automatically– from “smaller” to “larger” type

• Otherwise explicit casting og conversion must be applied:– Type cast: prefix the type name in parentheses

– Conversion: use the System.Convert-class

int i = 5;double d = 3.2;string s = "496";

d = i;

i = (int) d;

i = System.Convert.ToInt32(s);

implicit cast

Explicit cast is needed

Conversion

Page 15: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

15

Exercises

1. Lookup System.Convert in msdn2.microsoft.com

2. Write a small program that reads decimal number from the console (ReadLine()) and convert it to a double.

3. Round the number, so it has two decimals. (use integer division)

4. Write a small program that prints the number of 1000s, the number of 100s, the number of 10s and the number of 1s in the number 4623.

Page 16: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

16

C#- objects and classes

• The class is a type definition– Class members are: constructors, methods and instance

variables (like Java) and properties

• The object is the actual instance• Every class inherits from System.Object (object) –

also like Java– The class Object offers among other: ToString() and

Equals()

• Objects are created using the new operator (like Java)

Page 17: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

17

C#- Sample class

class HelloClass // class definition{

private string name; //instance variablepublic HellolClass(string name) //constructor{

this.name = name;}public void SayHello()//method{

Console.WriteLine("Hello "+name);}

}

Page 18: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

18

C#- use of the HelloClass

using System; //using classes in namespace System

namespace ConsoleApplication1{ //definition of a namespace class HelloClass{ //Class definition

private string name; //instance variable public HelloClass(string name){ //constructor

this.name = name; } public void SayHello(){ //method

Console.WriteLine("Hello "+name); }}class MainClass{ //Main-class containing the Main-method static void Main(string[] args){

HelloClass h = new HelloClass("Carl"); //instantiation or //creation of an object

h.SayHello(); //calling a method //on the object

}}

}

Page 19: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

19

C#- Namespaces and Using

• Namespaces is a tool for structuring programs and systems• Makes it possible to use the same names (identifiers) in

different parts of an application.• Namespaces may be nested• Visual Studio creates default a namespace with the same

name as the project• using <namespace name> tells the compiler where to look

for definitions that our program refers to• Namespaces are not the same as Java-packages, but they

are used for the same things and there are similarities

Page 20: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

20

C#- constructors

• Are called when an object is created:– HelloClass h = new HelloClass("Carl");– This constructor takes a parameter of type string

• The constructor’s job is to initialise the object, that is to assign valid values to the instance variables of the object

• A default-constructor is created automatically:– The default-constructor takes no arguments and initialises the

instance variables to their default values– The default-constructor may be overridden be writing a

constructor with no parameters

Page 21: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

21

C#- value- and reference-types

• Objects of value-type are stack allocated – objects of reference type are allocated on the heap

• Value types dies, when control goes out of the scope, where they are declared – reference types removed by the garbage collector

• Value types are copied with assignment – with reference types a reference (the address) is copied

Page 22: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

22

C#- reference types - example

• creation, assignment and comparison:

Customer c1, c2, c3;string s1, s2;

c1 = new Customer("Flemming Sander", 36259);c2 = new Customer(”Bjarne Riis", 55298);c3 = null; // c3 refers to nothing

c3 = c1; // c3 refers to the same object as c1

if (c1 == null) ... // is c1 referring to something? if (c1 == c2) ... // compare references if (c1.Equals(c2)) ... // compares object-values

Page 23: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

23

C#- When are objects equal?

• Classes ought to override the Equals-methodpublic class Customer{ . . .

public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // surely not equal

other = (Customer) obj; // explicit typecast return this.id == other.id; // equal if ids are... }}

Page 24: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

24

C#- Boxing and Unboxing

• C# converts automatically between simple value and object– value => object = "boxing“ (the value is “wrapped in a box”)

– object => value = "unboxing“ (the value is unwrapped again)int i, j;object obj;string s;

i = 32;obj = i; // boxing (copy)i = 19;j = (int) obj; // unboxing!

s = j.ToString(); // boxing!s = 99.ToString(); // boxing!

Page 25: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

25

C#- arrays

• Arrays are reference types– Created from the Array-class in FCL

– Created using the new-operator

– 0-based indexing

– Are initialised with default value (0 if numeric, null if reference)

int[] a;a = new int[5];

a[0] = 17;a[1] = 32;int x = a[0] + a[1] + a[4];

int l = a.Length;

Access element 1

Creation

Number of elements

Page 26: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

26

C#- enumerations

• Originally a C/C++ construction used to assigning symbolic names to numerical values:

enum Month {January= 1, February = 2,…,December = 12}public static void GetSeason(Month m){ switch(m) { case Month.January: Console.WriteLine(”Winter”);……

Page 27: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

27

C#- structs

• In some ways like a class, but there are differences:– Can have instance variables and methods– Cannot have a default constructor– Variables of a struct-type are value types and as such

stack allocated– Can only inherit from interfaces– Cannot be inherited from

• Can be used to implement ADTs, but no inheritance and polymorphism

Page 28: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

28

Decision Constructs

• To control the flow of program execution, C# defines two simple constructs to alter the flow of your program– The if/else statement

– The switch statement

• Like Java

Page 29: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

29

C#- selection and iteration

x = obj.foo();

if (x > 0 && x < 10) count++;else if (x == -1) ...else { ...}

while (x > 0){ ...

x--;} for (int k = 0; k < 10; k++)

{ ...}

Page 30: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

30

C#- foreach-loop

• foreach loop is used to sweep over collections as arrays– Reduces the risk of indexing errors

int[] data = { 1, 2, 3, 4, 5 };int sum = 0;

foreach (int x in data){ sum += x;}

foreach

type value collection

Page 31: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

31

C#- methods

• Much like Java – Example (Consider an Account-class with an instance variable bal):

public float GetBalance() { return bal;}

• Called on an object:iAccount myAccount= new Account();int saldo = minKonto.GetSaldo();

Page 32: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

32

Method Parameter Modifiers• C# provides a set of parameter modifiers that control how

arguments are sent into (and possibly returned from) a given method.

Page 33: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

33

The Default Parameter-Passing

// Arguments are passed by value by default.public static int Add(int x, int y){

int ans = x + y;// Caller will not see these changes // as you are modifying a copy of the// original data.x = 10000;y = 88888;return ans;

}

Page 34: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

34

The out Modifier

// Output parameters are allocated by the member.

public static void Add(int x, int y, out int ans)

{

ans = x + y;

}

static void Main(string[] args)

{

// No need to assign local output variables.

int ans;

Add(90, 90, out ans);

Console.WriteLine("90 + 90 = {0} ", ans);

}

Page 35: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

35

The ref Modifier

public static void SwapStrings(ref string s1,ref string s2)

{string tempStr = s1;s1 = s2;s2 = tempStr;

}static void Main(string[] args){

string s = "First string";string s2 = "My other string";Console.WriteLine("Before: {0}, {1} ", s, s2);SwapStrings(ref s, ref s2);Console.WriteLine("After: {0}, {1} ", s, s2);

}

Page 36: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

36

The params Modifier// Return average of 'some number' of doubles.static double CalculateAverage(params double[] values){

double sum = 0;for (int i = 0; i < values.Length; i++)

sum += values[i];return (sum / values.Length);

}static void Main(string[] args){

// Pass in a comma-delimited list of doubles...double average;average = CalculateAverage(4.0, 3.2, 5.7);Console.WriteLine("Average of 4.0, 3.2, 5.7 is: {0}", average);// ...or pass an array of doubles.double[] data = { 4.0, 3.2, 5.7 };average = CalculateAverage(data);Console.WriteLine("Average of data is: {0}", average);

}

Page 37: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

37

C#- Methods

• A class may have two kind of methods:– Instance methods– Static methods (class methods)– Instance methods need an object to be invoked– Static methods are called using the class name

only

Page 38: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

38

C#- Example

• The array-class in BCL (FCL)– The class is a member of namespace System (System.Array)

namespace System{ public class Array { public int GetLength(int dimension) { ... }

public static void Sort(Array a) { ... }

. . .

}}

instance method

static method

Page 39: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

39

C#- calling the methods

/* main.cs */

using System;

public class App{ public static void Main() { int[] data = { 11, 7, 38, 55, 3 }; Array.Sort(data);

for (int i=0; i<data.GetLength(0); i++) Console.WriteLine(i + ": " + data[i]); }}

Class-method Instance-

method

Page 40: Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection

Spring 2007 NOEA: Computer Science Programme

40

ExercisesWrite a driver-class that test the following methods:1. A method that returns the sum the elements in an array2. A method that returns the average of the elements in an

array3. A method that returns the number of elements with the

value 7 in an array4. A method that returns true if the value 3 is contained in

the array and false otherwise5. Generalise your solution to exercise 2 and 3, so the value

in question (7 and 3 resp.) is passed as an argument to the method.

6. Cpr.htm7. Find some of your old Java-programs and translate them

into C#