classes, inheritance, interfaces, polymorphism simple and structured types, generics type safeness

Similar documents
Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects

Object Oriented Programming

Object Oriented Programming

..to the Berlin BAU Software Lab! Let's have two interesting weeks together! (c)schmiedecke C# and.net

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Object-Oriented Programming

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduction to Programming Using Java (98-388)

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

.Net Technologies. Components of.net Framework

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

C#: framework overview and in-the-small features

Object-Oriented Programming in C# (VS 2015)

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java.

Uka Tarsadia University MCA ( 3rd Semester)/M.Sc.(CA) (1st Semester) Course : / Visual Programming Question Bank

6: Arrays and Collections

Object-Oriented Programming in C# (VS 2012)

Course Hours

6: Arrays and Collections

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Industrial Programming

Absolute C++ Walter Savitch

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

Chapter 5 Object-Oriented Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

Chapter 1 Getting Started

Introduction to C# Applications

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

Index COPYRIGHTED MATERIAL

WA1278 Introduction to Java Using Eclipse

Java Object Oriented Design. CSC207 Fall 2014

Problem Solving with C++

Distributed Systems Recitation 1. Tamim Jabban

OVERVIEW ENVIRONMENT PROGRAM STRUCTURE BASIC SYNTAX DATA TYPES TYPE CONVERSION

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

C++ (Non for C Programmer) (BT307) 40 Hours

Cloning Enums. Cloning and Enums BIU OOP

Distributed Systems Recitation 1. Tamim Jabban

An Introduction to C++

DigiPen Institute of Technology

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

EEE-425 Programming Languages (2013) 1

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C#

Course Syllabus C # Course Title. Who should attend? Course Description

CHAPTER 1: INTRODUCING C# 3

1 Shyam sir JAVA Notes

CMSC 132: Object-Oriented Programming II

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Introduction to Inheritance

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Introduction to Programming Microsoft.NET Applications with Visual Studio 2008 (C#)

DAD Lab. 1 Introduc7on to C#

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Microsoft. Microsoft Visual C# Step by Step. John Sharp

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

RTL Reference 1. JVM. 2. Lexical Conventions

C#: advanced object-oriented features

COP 3330 Final Exam Review

Programming in Visual Basic with Microsoft Visual Studio 2010

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

C#: advanced object-oriented features

Classes. System. class String // alias for string

CHAPTER 1: INTRODUCTION TO THE IDE 3

CS260 Intro to Java & Android 03.Java Language Basics

DC69 C# and.net JUN 2015

Question And Answer.

DESIGN PATTERN - INTERVIEW QUESTIONS

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Collections, Maps and Generics

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

CS201 - Introduction to Programming Glossary By

Advanced Programming Methods. Lecture 9 - Generics, Collections and IO operations in C#

NOIDATUT E Leaning Platform

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Chapter 02 Building Multitier Programs with Classes

Tokens, Expressions and Control Structures

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

C# Programming in the.net Framework

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Language Features. 1. The primitive types int, double, and boolean are part of the AP

.NET-6Weeks Project Based Training

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Short Notes of CS201

STRUCTURING OF PROGRAM

Core Java Syllabus. Pre-requisite / Target Audience: C language skills (Good to Have)

Transcription:

C# is an object oriented language very much like Java a little more modern (int is an object) much more features and add-ons (to keep experienced programmers happy) classes, inheritance, interfaces, polymorphism simple and structured types, generics type safeness beautiful GUIs phantastic ready-made data types great libraries easy networking and webworking (efficient graphics processing) (c)schmiedecke 13. 1 - C# and.net 2

value objects reference parameters block matrices unified type system properties indexer iterators delegates lambda expressions data queries don't worry, be happy! (c)schmiedecke 13. 1 - C# and.net 3

CLS and CTS C#.NET J#.NET C++.NET VB.NET CIL CLR Windows (c)schmiedecke 13. 1 - C# and.net 4

.NET no specific meaning, suggests web distribution current version: 4.0 CLS Common Language Specification specifies similar behaviour in.net languages e.g. parameter passing, argument evaluation, exception handling CTS Common Type System guarantees loss-free data exchange between.net languages CIL Common Intermediate Language Bytecode for efficient execution on Windows systems CLR Common Language Runtime executes CIL (c)schmiedecke 13. 1 - C# and.net 5

Breakpoint Editor Solution Explorer Output (c)schmiedecke 13. 1 - C# and.net 6

F5 shift+f5 Ctrl+F5 F11 F10 Shift+F11 F11 Step into F10 Step over Shift+F11 Step out Alt+Shift*Break Interrupt F5 Resume Shift+F5 Terminate Ctrl+F5 Restart (c)schmiedecke 13. 1 - C# and.net 7

(c)schmiedecke 13. 1 - C# and.net 8

(c)schmiedecke 13 C#-3-OO 9

Classes are types are "blueprints" for objects (heap objects, indefinite scope) can form type hierarchies by inheritance Namespaces are "containers" for types (classes -- and interfaces, enumerations, structs, delegates) may be nested determine their members' fully qualified name public classes (etc.) can be used, if they are referenced i.e. their path is known to the project using is a shorthand to omit the namespace path of a classname it is not an act of import! (c)schmiedecke 13 C#-2 - Classes and Objects 10

The following class definitions are equivalent: using System.IO; namespace fileutils { public class FileInformation { public void PrintFileInformation(string filename) { if (File.Exists(filename)) { string fileinfo = RetrieveFileInfo(filename); //... } } } } namespace fileutils { public class FileInformation { public void PrintFileInformation(string filename) { if (System.IO.File.Exists(filename)) { string fileinfo = RetrieveFileInfo(filename); //... } } } } (c)schmiedecke 13 C#-2 - Classes and Objects 11

C# Constructors (Destructors) Fields Properties Indexer Events Methods Overloaded Operators Inner Types JAVA Constructors Fields Methods Inner Types (c)schmiedecke 13 C#-2 - Classes and Objects 12

variables, instance and static should be private, for internal use only naming convention: camelcase (start with small letter) extra modifiers for constants: const (compiletime value) static const (global constant) readonly (immutable after initialization) (usually) public class Person { private char internalstatus; // cryptic on purpose private static int currentwaitingtime; public const int ID; } (c)schmiedecke 13 C#-2 - Classes and Objects 13

Programming best practice in all oo programs! private fields with get and set accessors preserve consistent state! shorthand declaration in C# readonly by providing a private setter or no setter at all class Person { private char internalstatus; // cryptic on purpose private static int currentwaitingtime; } private int id; public int Id { get { return id; } set { id = value; } } //automatic property: public int Id { get ; set } //with resticted access public int Id { get ; private set } (c)schmiedecke 13 C#-2 - Classes and Objects 14

Use Properties for robustness every setter checks for validity SetTime can simply use setters use of getters and setters is implicit: Hour = h; // setter is called return string.format( "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second ); // getter is called (c)schmiedecke 13 C#-2 - Classes and Objects 15

void methods and functions like in Java naming convention PascalCase methods can take parameters and throw and handle exceptions (without declaring them) an instance method reads or modifies "its" instance fields a static method gets ist data from parameters. public class BankAccount { private decimal Balance; private decimal DebtLimit; private decimal Transit; public void Add(decimal amount) { } public void Transfer(decimal amount, BankAccount acc) { if (Balance + DebtLimit < amount) throw new BankingException(); Transit=amount; acc.add(amount); Transit=0; } } (c)schmiedecke 13 C#-2 - Classes and Objects 16

Each object has an identity a state, with characteristic features (constants) and changing features (properties) state initialization at object construction using a constructor (or direct initialization) implicit default constructor initializes to 0, false and null public class NewTime { public NewTime(int h, int, m, int s) // constr. w/ 3 params { SetTime(h, m, s); } public NewTime(int h) : this(h, 0, 0){ } // using constructor // initializer : this //... } (c)schmiedecke 13 C#-2 - Classes and Objects 17

Overloading: "Defining another method using the same name, but different parameters, either in number or type." C# allows for constructor overloading method overloading operator overloading implicit default constructor initializes to 0, false and null overloading constructors remove implicit constructor when overloading, make sure to add a default constructor! (c)schmiedecke 13 C#-2 - Classes and Objects 18

Constuctor definition like a method with name of class. Constructor overloading: Define more than one constructor. Constructor initializer: reuse another constructor (rather than redundantly redifining it) using :this( ) - body starts with calling other constructor. public class NewTime { public NewTime(int h, int, m, int s) // constr. w/ 3 params { SetTime(h, m, s); } public NewTime(int h) : this(h, 0, 0){ } // using constructor // initializer : this //... } (c)schmiedecke 13 C#-2 - Classes and Objects 19

Time has no overloaded constructors but public properties that should be initialized Object initilizers "invent" a constructor by calling it using the names of the properties as parameter names no need to mention all, others initialized to 0 / false / null Time MyTime = new Time(Hour=11, Minute=15, Second=0); Time YourTime = new Time(Hour=14); // all others 0 (c)schmiedecke 13 C#-2 - Classes and Objects 20

Test Methods are static instantiate the class under testing assign values to ist fields an properties legal and forbidden ones! call all methods with different parameters lagal and forbidden ones! check and output the result. Collect Test Methods in a static Test Class In the Main method, call the different tests and evaluate them. (c)schmiedecke 13 C#-2 - Classes and Objects 21

Must be static Must be members of a static class Can only access public properties and methods of the extended class. public static class TimeExtensions { public static Time AddHours( this Time tm, int hours) { Time newtime = new Time(tm.Hour, tm.minute, tm.second); newtimehour = (tm.hour + hours) % 24; return NewTime; } } Time mytime = new Time (22, 12, 08); mytime = mytime.addhours(3); Console.WriteLine(mytime); // 01:12:08 (c)schmiedecke 13 C#-2 - Classes and Objects 22

Warning! A n instance method with the same signature HIDES the extension So, if later on, a similar method is added to the class or to one of ist superclasses, your extension method will no longer be called! (c)schmiedecke 13 C#-2 - Classes and Objects 23

none, internal accessible within assembly (=project) OR public accessible from anywhere static contains only static members abstract only for subclassing, no instantiation OR sealed subclassing prohibited OR none find contradicting combinations! (c)schmiedecke 13 C#-2 - Classes and Objects 24

public accessible anywhere none, internal accessible within assembly (=project) protected accessible in subclasses private accessible within class (even other instances) static member belongs to class, not instance abstract not for fields virtual method: open for polymorphic overriding override method: polymorphic overriding const field: compiletime constant readonly field: immutable after initialization (c)schmiedecke 13 C#-2 - Classes and Objects 25

static fields are not specific to instances the type manages them for all instances (family property) Class Windsor Chief: Queen E II Res: Buckingham P Home: Windsor C. static methods cannot access the instance use static fields, call static methods receive data via parameters create instance to call instance methods Charles William Elizabeth II static classes Kate contain only static members (c)schmiedecke 13 C#-2 - Classes and Objects 26

could Compute day of the week for a given Date Convert Date to other calendar Validate a Date Compute next leap year for a given Date Provide national output formats for Date All makes sense without storing a Date, i.e. without an instance state. (But it would also make sense as instance methods) static class DateUtilities { public static string DayOfTheWeek(Date date) {...} public static bool IsValidDate (int day, int month, int year) { } } (c)schmiedecke 13 C#-2 - Classes and Objects 27

Classes from different namespaces: add "using" directive using OrganizerBackend; Classes from different projects or solutions, or from libraries add Reference to your project (c)schmiedecke 13 C#-3-OO 28

(c)schmiedecke 13 C#-3-OO 29

int, double, char, bool byte, sbyte, short, ushort, uint, long, ulong float, decimal string are.net-types, defined in the System namespace are Objects All are.net-types, i.e. common to all.net languages All expected implicit and explicit number conversions double val = 3; // implicit conversion from int to double int size = (int)33.1234 // explicit converion (c)schmiedecke 13 C#-3-Data and Objects 30

Static class System.Convert does it almost always overflow-checked Names of.net Types Convert.ToBoolean(val) Convert.ToByte(val) Convert.ToChar(val) Convert.ToDecimal(val) Convert.ToInt32(val) Convert.ToString(val)... //val can be any type that "works" exception, if value does not fit (c)schmiedecke 13 C#-3-Data and Objects 31

class Names { string firstname; string surname; public Names(string firstname, string surname) { } public static implicit operator Name(Names names) { return new Name(names.surname + ", "+names.firstname); } class Name { string Name; public Name(string name) { this.name = name; } public static explicit operator Names(Name name) { string[] words = name.split(','); return new Name(words[1], words[0]); } } ------------------------------------------- Names mynames = new Names("Ilse", "Schmiedecke"); Name myname = names; // implicit conversion Names reconstructed = (Names)myName; // explicit conversion (c)schmiedecke 13 C#-3-Data and Objects 32

Use Constructor to create a new Object with "old" content string[] mywords = { "All", "my", "words", "and", "ideas" }; List<string> morewords = new List<string> (mywords); public class List<T> { public List<T>(T[] array) { foreach (T t in array) this.add(t); } } (c)schmiedecke 13 C#-3-OO 33

Simple Types own operators +(a,b) identical to a+b Operators are like global static methods Operators can be user-defined through overloading: public static bool operator+ (MyType x, MyType y) { return Combine (x, y); } Operators are functions, i.e. they must return a value (c)schmiedecke 13 C#-3-Data and Objects 34

Simple Types are Value Types Class Instances are Reference Types a: c: 100 int a = 100; Cloud c = new Cloud(); But Simple Types are objects, too? (c)schmiedecke 13 C#-3-Data and Objects 35

Structs encapsulate data types like classes no "default" constructor simply declare a variable! custom constructors possible (for initialization) no type hierarchy Contain just like classes: Fields (static and instance), Properties Methods Delegates Indexer (c)schmiedecke 13 C#-3-Data and Objects 36

Use Struct without constructor struct Car { int Power; string Type; int YearOfProduction; int age { get {return CurrentYear-YearOfProduction; }} } Car mynewcar; // no constructor needed mynewcar.power = 25; mynewcar.type = "Trabant"; (c)schmiedecke 13 C#-3-Data and Objects 37

Class object with own lifecycle, stored on heap inheritance and polymorphism new (constructor call) required for object construction Stuct: Data Structure, stored directly in a variable Lifecycle depends on the variable no inheritance, no polmorphism no parameterless constructor; construction by declaration, "new" optional for initialization (c)schmiedecke 13 C#-3-Data and Objects 38

struct Car { int Power; string Type; int YearOfProduction; int age { get {return CurrentYear-YearOfProduction; }} } public void method() { Car mynewcar; mynewcar.power = 25; mynewcar.type = "Trabant"; } // mynewcar is lost! public void method(car paramcar) { paramcar.power = 25; paramcar.type = "Trabant"; } // paramcar is lost! (c)schmiedecke 13 C#-3-Data and Objects 39

Class Limousine{ int Power; string Type; int YearOfProduction; int age { get {return CurrentYear-YearOfProduction; }} } public void method() { Limousine mynewcar; mynewcar.power = 25; mynewcar.type = "Trabant"; } // mynewcar is lost! public void method(limousine paramcar) { paramcar.power = 25; paramcar.type = "Trabant"; } // paramcar is modified and survives! (c)schmiedecke 13 C#-3-Data and Objects 40

Reference type objects live as long as they are referenced Value type objects are destroyed when execution leaves the surrounding block. Value parameters are copied into the method method has no effect on them Reference parameters are referred to by the method method can have effect on them class Names { string firstname; string surname; } struct Name { string name; static void deleteentries(names names, Name name) { names.firstname = "deleted"; // reference Type deleted names.surname = "deleted"; name.name = "deleted"; // value type only copy deleted } } (c)schmiedecke 13 C#-3-Data and Objects 41

static void Main() { Person Annie = new Person("smith, annie"); Person Bruce = new Person("wild, bruce"); Exchange(Annie, Bruce) Console.WriteLine(Annie.Name, Bruce.Name); } static void Exchange (Person A, Person B) { Person C = A; A = B; B = C; } // no effect! { string c = A.Name; A.Name = B.Name; B.Name = c; } Annie Bruce smith, annie wild, bruce A B C Parameter passing by (reference) value copies to local variables (c)schmiedecke 13 C#-3-OO 42

Enumerations are types of small sets of named values Mapped to integers, can be changed to long, short, byte. Explicit mapping is possible arithmetics are allowed (even if "overflowing" the enum!) automatic ToString() and static Parse(Type, string) method public enum Weekday { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } // mapped to 0-6 private enum Day : byte // only 1 byte long { Sun=1, Mon, Tue, Wed, Thu, Fri, Sat } // mapped to 1-7 Weekday today = Weekday.Wednesday; if (today > Weekday.Friday) Shout("Weekend!"); (c)schmiedecke 13 C#-3-Data and Objects 43

(c)schmiedecke 13 C#-3-OO 44

Collections are sets of data stored under a common name Arrays: Data of identical type stored in a fixed-size area in memory, accessed by indeces. General Collections: Classes for storing varying amounts of data different access strategies different special properties (c)schmiedecke 13 C#-3-Data and Objects 45

Arrays contain data of identical type access via numerical index, starting with O overflow and underflow cause exceptions dimensioning as "jagged arrays": type [][][] System.Array provides poperty Length int[][] jagged = new int[3][]; jagged[0] = new int[2]; jagged[0][0] = 1; jagged[0][1] = 2; jagged[1] = new int[1]; jagged[2] = new int[3] { 3, 4, 5 }; for (int i = 0; i < jagged.length; i++) { int[] innerarray = jagged[i]; foreach (int number in innerarray) { Console.Write(number + " "); } Console.WriteLine(); } (c)schmiedecke 13 C#-3-Data and Objects 46

Block arrays are defined as type [,,, ] Length property of class Array applies in total GetLength method gives dimension lengths Block arrays are nicer, but slower then jagged arrays static void Main() { int[,,] threedimensional = new int[3, 5, 4]; threedimensional[0, 0, 0] = 1; threedimensional[0, 1, 0] = 2; threedimensional[0, 2, 0] = 3; threedimensional[0, 3, 0] = 4; threedimensional[0, 4, 0] = 5; threedimensional[1, 1, 1] = 2; threedimensional[2, 2, 2] = 3; threedimensional[2, 2, 3] = 4; } for (int z = 0; z < threedimensional.getlength(2); z++) { for (int y = 0; y < threedimensional.getlength(1); y++) { for (int x = 0; x < threedimensional.getlength(0); x++) { Console.Write(threeDimensional[x, y, i]); } Console.WriteLine(); //lines of 3 values } Console.WriteLine(); // blocks of 5 lines } Console.Writeline("Total Length: "+ threedimensional.length); // 60 (c)schmiedecke 13 C#-3-Data and Objects 47

Properties pretend to be fields - but are secured Indexers let classes pretend to be arrays: Object can be accessed using square brackets "index" needs not be numerical, though class FakeArray { this string [int index] { get { int choice = index % 3; if (choice == 0) return "cow"; else if (choice == 1) return "dog"; else return "cat"; } private set {} } } FakeArray myarray = new FakeArray(); string mystring = myarray[18]; // cow mystring = myarray[2]; // cat myarray[22] = "spider"; // ignored... (c)schmiedecke 13 C#-3-Data and Objects 48

string has an indexer you can access individual chars using square brackets string word = "Mysecretcodeword"; char firstletter = word[0]; We will learn about List-type collections All Lists have indexers so you can access any List object as if it was an array and many more (c)schmiedecke 13 C#-3-Data and Objects 49

class Class Model IEnumerable + GetEnumerator() : Enumerator ICollection - Count: int + CopyTo() : ICollection IList - IsFixedSize: boolean - IsReadOnly: boolean - this: IList IDictionary - IsFixedäSize: boolean - IsReadOnly: boolean - Keys: ICollection - this: IDictionary - Values: ICollection + Add() : void + Clear() : void + Contains() : boolean + Add() : void + IndexOf() : int + Clear() : void + Insert() : void + Contains() : boolean + Remove() : void + GetEnumerator() : Enumerator (c)schmiedecke 13 + RemoveAt() : void C#-3-Data and + Objects Remove() : void 50

Namespace System.Collections IEnumerable foreach loop is applicable ICollection allows copying between Collections IList indexed collections, fixed order Indexes IDictionary associative Collection, mapping keys to Values static void Main() { int[] arr = new int[3]; arr[0] = 2; arr[1] = 3; arr[2] = 5; LinkedList list = new LinkedList(arr); // Copy to List Hashmap map = new Hashmap() hashmap.add("key1", "value1"); ArrayList list2 = new ArrayList(); map.copyto(list2); // Copy to List (c)schmiedecke 13 C#-3-Data and Objects 51

Indexers make objects accessable like arrays Declare "this" property (getter and setter) index may be any type, most commonly int overloading possible! class MockArray { private string low = "low", high = "high"; public string this[int index] { get { if (index < 0) throw new IndexOutOfRangeException(); else if index < 10 ) return low; else return high; } set { if (index < 0) throw new IndexOutOfRangeException(); else if index < 10 ) low = value; else high = value; } } MockArray mock = new MockArray(); mock[12] = mock[8]; (c)schmiedecke 13 C#-3-Data and Objects 52

Lists are flexible numbered Collections with fixed order of elements Accessable using an Indexer Most important IList-Implementations ArrayList, Linkedlist, Array SortedList Stack, Queue ArrayList list = new ArrayList(); list.add(2); list.add(3); list.add(7); foreach (object prime in list) Console.WriteLine((int)prime); for (int i = 0; i < list.count; i++) Console.WriteLine((int)(list[i])); list.add(13); list.insert(3, 11); // foreach loop // indexer access (c)schmiedecke 13 C#-3-Data and Objects 53

IDictionary describes Maps, or associative collections Key-Value-Pairs Hashtable implements IDictionary Hashtable hashtable = new Hashtable(); hashtable.add("area", 1000); hashtable.add("perimeter", 55); hashtable.add("mortgage", 540); hashtable["year of construction"] = 1955; // Indexer if (hashtable.contains("area")) int area = (int)hashtable["area"]; foreach (object key in hashtable.keys) Console.WriteLine(key.ToString + ": " + hashtable[key].tostring()); (c)schmiedecke 13 C#-3-Data and Objects 54

class CollectionsGeneric IEnumerable<T> + GetEnumerator() : Enumerator<T> class Class Model IEnumerable + GetEnumerator() : Enumerator ICollection<T> - Count: int - IsReadOnly: boolean + Add() : void + Clear() : void + Contains() : boolean + CopyTo() : ICollection<T> + Remove() : void IList - IsFixedSize: boolean - IsReadOnly: boolean - this: IList + Add() : void + Clear() : void + Contains() : boolean + IndexOf() : int + Insert() : void + Remove() : void + RemoveAt() : void ICollection - Count: int + CopyTo() : ICollection IDictionary - IsFixedäSize: boolean - IsReadOnly: boolean - Keys: ICollection - this: IDictionary - Values: ICollection + Add() : void + Clear() : void + Contains() : boolean + GetEnumerator() : Enumerator + Remove() : void IList<T> IDictionary<T, Key> - this: IList<T> - Keys: ICollection<T> - this: IDictionary<T, Key> + IndexOf() : int - Values: ICollection<T> + Exists() : void + Insert() : void + Add() : void + RemoveAt() : void + ContainsKey() : boolean (c)schmiedecke 13 + TryGetValue() : <T> C#-3-Data and Objects 55

Generic Collections result from a review process type safe access thread safe access much better performance Dictionary<string, int> dict = new Dictionary<string, int>(); dict.add("area", 1000); dict.add("perimeter", 55); dict.add("mortgage", 540); dict["year of construction"] = 1955; // Indexer if (dict.containskey("area")) int area = dict["area"]; // no type casting foreach (string key in dict.keys) Console.WriteLine(key + ": " + dict[key]()); (c)schmiedecke 13 C#-3-Data and Objects 56

Get all the Appointments today as a List List<Appointment> datalist = new List<Appointment>(); foreach (Appointment app in myorganizer.entries) if (app.date.compareto(datetime.now) == 0) list.add(app); var result = from app in myorganizer.entries where app.date.compareto(datetime.now) == 0 select app; List<Appointment> datalist = result.tolist<appointment>(); (c)schmiedecke 13 C#-3-OO 57

(c)schmiedecke 13 C#-3-OO 58

class TypeHierarchy IEnumerable IEnumerable<T> ICollection ICollectio<T> IDictionary IList HashTable ArrayList LinkedList ILst<T> IDictionary<T> ArrayList<T> List<T> Dictionary<T> (c)schmiedecke 13 C#-3-OO 59

Interfaces serve as common types for varying implementations a programming "contract" Examples: allow a prototype implementation to be replaced by a production implementation without effect on code tell another programming team what I expect from them specify the contents of a library or have a common variable type for a variety of values. public interface IRegister { public bool isexpired(datetime date); // abstract method } (c)schmiedecke 13 C#-3-OO 60

Gain flexibility: Use superclasses as variable types to allow for compatibility! Even better: use Interface type variables! IRegister<T> mylist = new RegisterPrototype<T>(); // simply replace by SecureRegister later. Careful with Generics! general and generic types are not directly compatible ArrayList list = new ArrayList<string>; // Compiler error! (c)schmiedecke 13 C#-3-OO 61

Like in Java, Interfaces are fully abstract classes can extend further interfaces public or internal members automatically public abstract abstract methods abstract properties abstract indexers abstract events (later) public interface IGroupList : IEnumerable { } int Count { get; set } // abstract Property IClassList this[int index]; // abstract Indexer int Find(string name); // abstrac Method void remove(int index); void add(person p); (c)schmiedecke 13 C#-3-OO 62

Adapter: your travelagency software was using an old routing library you want to move on to a modern open-source version expose the requirements of your software as an interface write an Adapter class to implement the interface with the new library class Adapter class Adapter Trav elagency OldRouting Trav elagency IOldRouting + computeroute() : string[] + computeroute() : string[] RoutingAdadpter NewRouting + getruotings() : Route[] IOldRouting routing = new RoutingAdapter(); routing.computeroute(destinatiolist); (c)schmiedecke 13 C#-3-OO 63

Why didtravelagency not use an interface (IOldRouting) from the beginning? less dependant on the OldRoutingClass Dependency complicates change DIP: Program against interfaces to reduce dependency Always design interfaces for your classes! IList<Route> routelist = new LinkedList<Route>(); // very easy to change to ArrayList or another implementation // very easy to use a verbose debugging type instead during // implementation (c)schmiedecke 13 C#-3-OO 64

Proxy a client class refers to a "costly" object e.g. an image which needs downloading resources as long as the object is not really used, a mockup will do: Proxy when needed, the mockup will "secretly" get the object and delegate access. class Adapter class Adapter Photov iiewe Image Photov iiewe IImage + displayimage() : void + displayimage() : void ImageProxy + displayimage() : void Image + displaimage() : void class ImageProxy : IImage { void displayimage() { // download image when called Image img = loadimage(); img.displayimage(); } } (c)schmiedecke 13 C#-3-OO 65

These "Tricks" are well-known Design Patterns Every software professional must know them Good solutions to frequent problems Well-knowns structures improve code readability Original List by Gamma, Helm, Johnson and Vlissides Called Gang of Four Patterns or GoF Patterns (c)schmiedecke 13 C#-3-OO 66

Just like in Java A class can only inherit from ONE superclass but implement any number of Interfaces some Interfaces are empty "marker interfaces" test for type possible: mylist is ISerializable Interface IEnmuerable { Enumerator getenumerator(); } Interface IEnumerable<T> : IEnumerable { Enumerator<T> get Enumerator(); // addtional method } Interface ISerializable {} // empty marker interface class RandomEnumerator : IEnumerable<T>, ISerializable { } (c)schmiedecke 13 C#-3-OO 67

Interfaces are fully abstract Abstract classes are partly implemented specific methods open for implementation in subclasses Design Pattern: Template Method public abstract class Logger { string log; public void log(string logentry) { log += logentry } } public void closelog() { Save(); Clear(); } // template meth. abstract void Save(); public class FileLogger : Logger { public override void Save() { SendToFile(".\logfile.lg", log); } } (c)schmiedecke 13 C#-3-OO 68

In C#, not all methods areoverridden polymorphically. For Polymorphism: in the Superclass: Mark method as "virtual" in the Subclass Mark method as "override" Best Example: ToString() method public class Object { public virtual string ToString() { } } public class Appointment // : object { public override string ToString() { return this.name + ; } } (c)schmiedecke 13 C#-3-OO 69

Polymorphism, Dynamic Binding: method of instance type is called i.e. subclass method object appointment = new Appointment(); s = appointment.tostring(); // overridden ToString is called, i.e. as defined in the // Appointment class Static Binding method of the reference type (i.e.the variable) is called i.e. superclass method ( in this case, it would be the ToString-method in object. ) (c)schmiedecke 13 C#-3-OO 70

(c)schmiedecke 13 C#-3-OO 71

Historically: transforming input data to output data Waiting for the program to finish in order to get the result printout endless loops were desastrous. Today mainly: working interactively on complex information information only accessable via the program basically performing an endless loop waiting for user interaction Both need files to persist data while the program is not running. (c)schmiedecke 13 C#-3-OO 72

Streams are about getting data into a program out of a program Class Stream is abstract A Stream has a position current position end position Concrete Streams point to a Source/Destination FileStream NetworkStream MemoryStream (c)schmiedecke 13 C#-3-OO 73

Create a StreamObject Use it Close it!!! string filename = @"C:\Temp\programdata.txt" ; Stream myfilestream = new FileStream(filename); myfilestream.writebyte('a'); myfilestream.close(); or use "auto closing" using (Stream myfilestream = new FileStream(filename)) { myfilestream.writebyte('a'); } (c)schmiedecke 13 C#-3-OO 74

BufferedStream don't forget to call Flush CryptoStream uses encryption! GzipStream Compressed source/destination Stream myfilestream = new FileStream(filename); GzipStream myzippedstream = new GzipStream(myFileStream); (c)schmiedecke 13 C#-3-OO 75

Abstract classes Reader and Writer specific direction much better functionality TextReader StreamReader StringReader TextWriter StreamWriter StringWriter StreamReader mystreamreader = new StreamReader(myFileStream); (c)schmiedecke 13 C#-3-OO 76

Writing binary data Class BinaryFormatter Can write numbers and other data i.e. any Object from a Serializable class Mark class as Serializble: [Serializable] or write your own Serialization by implementing ISerializable BinaryFormatter formatter = new BinaryFormatter(); try { myappointment = // save formatter.serialze(outputstream, myappointment); // modify myappointment = null; // restore myappointment = (Appointment)formatter.Deserialize(inputStream); } catch (IOException e) { Console.WriteLine("Persistence Failure"); } (c)schmiedecke 13 C#-3-OO 77

Exceptions are likely peripherical devices do fail at times catch IOExceptions!! Close your Streams! as long as it is open, it cannot be reused! use the using block with auto-closing! Binary Streams are illegible during development, work with Text Streams you can even edit the input files in the file system! (c)schmiedecke 13 C#-3-OO 78

Important data must "persist" (i.e. survive) between program newstarts Write the to files or to a Database Load Data on program start Save Data frequently during execution, to safeguard for program crashes e.g. wth every saving operation on memory (c)schmiedecke 13 C#-3-OO 79

C# is a powerful OO language with a powerful IDE for "visual" development Even in OO programming, it is all about Data in Value and Reference Types in Arrays in Basic and Generic Collections in Files and Databases as Input from a GUI Strong Types make Programming Safe but we need a lot of conversion techniques to remain flexible (c)schmiedecke 13 C#-3-OO 80

(c)schmiedecke 13 C#-3-OO 81