C# The New Language For.NET

Similar documents
9 A Preview of.net 2.0

Distribution and Integration Technologies. C# Language

C# Java. C# Types Naming Conventions. Distribution and Integration Technologies. C# C++.NET A C# program is a collection of: C C++ C# Language

3. Basic Concepts. 3.1 Application Startup

Object-Oriented Programming in C# (VS 2015)

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

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

Object-Oriented Programming in C# (VS 2012)

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

Introduction to Programming Using Java (98-388)

Introduction to C# Applications

Game Engineering: 2D

.Net Technologies. Components of.net Framework

Object-Oriented Programming

Short Notes of CS201

PES INSTITUTE OF TECHNOLOGY

NOIDATUT E Leaning Platform

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

CS201 - Introduction to Programming Glossary By

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

DigiPen Institute of Technology

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?

Chapter 1 Getting Started

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

Table of Contents Preface Bare Necessities... 17

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

C# Programming in the.net Framework

Object-oriented Programming. Object-oriented Programming

CS260 Intro to Java & Android 03.Java Language Basics

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

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

CMSC 132: Object-Oriented Programming II

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

Language Specification

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

C# machine model. Programming Language Concepts and Implementation Fall 2011, Lecture 2. Rasmus Ejlers Møgelberg

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

EEE-425 Programming Languages (2013) 1

Self-review Questions

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

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

1 Shyam sir JAVA Notes

Introduction To C#.NET

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

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

VALLIAMMAI ENGINEERING COLLEGE

Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004

DAD Lab. 1 Introduc7on to C#

Industrial Programming

Multiple Choice: 2 pts each CS-3020 Exam #3 (CH16-CH21) FORM: EX03:P

Course Hours

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CMSC 132: Object-Oriented Programming II

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Index COPYRIGHTED MATERIAL

September 10,

IC Language Specification

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

G Programming Languages - Fall 2012

Tokens, Expressions and Control Structures

Instantiation of Template class

In this chapter, we will delve into types and type members.

Programming Language Concepts: Lecture 2

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CSE 307: Principles of Programming Languages

Java Primer 1: Types, Classes and Operators

IT 374 C# and Applications/ IT695 C# Data Structures

Java: introduction to object-oriented features

SWE344. Internet Protocols and Client-Server Programming

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

C # Language Specification

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Array. Prepared By - Rifat Shahriyar

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Applied object oriented programming. 4 th lecture

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime

Object Oriented Programming

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

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

Object Oriented Software Design II

C# and Java. C# and Java are both modern object-oriented languages

Absolute C++ Walter Savitch

Framework Fundamentals

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

C# s A Doddle. Steve Love. ACCU April 2013

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Implementing Subprograms

C# Language Reference

C# Language Specification

CS558 Programming Languages

Transcription:

secure: [si-'kyur] 1: free from danger 2: free from risk of loss 3: affording safety C# The New Language For.NET Andreas Schabus Academic Relations Microsoft Österreich GmbH andreas.schabus@microsoft.com http://blogs.msdn.com/msdnat Based on Slides by Prof. Dr. H. Mössenböck University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

Features of C# Very similar to Java 70% Java, 10% C++, 5% Visual Basic, 15% neu As in Java Object-orientation (single inheritance) Interfaces Generics (more powerful than in Java) Exceptions Threads Namespaces (similar to Java packages) Strong typing Garbage collection Reflection Dynamic loading of code... As in C++ Operator overloading Pointer arithmetic in unsafe code Some syntactic details

New Features in C# Really new (compared to Java) Call-by-reference parameters Stack-allocated objects (structs) Block matrices Enumerations Uniform type system goto statement Attributes System-level programming Versioning "Syntactic Sugar" Component-based programming - Properties - Events Delegates Indexers foreach loop Boxing / unboxing...

Hello World Program File Hello.cs using System; class Hello { static void Main() { Console.WriteLine("Hello World"); imports the namespace System entry point must be called Main prints to the console file name and class name need not be identical. Compilation (from the Console window; produces Hello.exe) csc Hello.cs Execution Hello

Structure of C# Programs Programm File1.cs File2.cs File3.cs namespace A {... namespace B {... namespace C {... class X {... class Y {... class Z {... If no namespace is specified => anonymous default namespace Namespaces may also contain structs, interfaces, delegates and enums Namespace may be "reopened" in other files Simplest case: single class, single file, default namespace

A Program Consisting of 2 Files Counter.cs class Counter { int val = 0; public void Add (int x) { val = val + x; public int Val () { return val; Prog.cs using System; class Prog { static void Main() { Counter c = new Counter(); c.add(3); c.add(5); Console.WriteLine("val = " + c.val()); Compilation csc /target:exe Counter.cs Prog.cs Execution Prog Working with DLLs csc /t:library Counter.cs => generates Counter.dll csc /r:counter.dll Prog.cs => generates Prog.exe

SYMBOLS

Identifiers Syntax Identifier = (letter '_' '@') {letter digit '_'. Unicode! Case-sensitive "@" can be used to treat keywords as identifiers - if... keyword - @if... identifier if May contain Unicode escape sequences (e.g. \u03c0 for p) Examples somename sum_of3 _10percent @while p \u03c0 b\u0061ck the identifier while the identifier p the identifier p the identifier back

Naming Conventions Casing Words are capitalized (z.b. ShowDialog) First letter in upper case, except for private or local variables, constants and fields constants upper case SIZE, MAX_VALUE local variables lower case i, top, sum private fields lower case data, lastelement public fields upper case Width, BufferLength properties upper case Length, FullName enumeration constants upper case Red, Blue methods upper case Add, IndexOf types upper case StringBuilder (predefined types in lower case: int, string) namespaces upper case System, Collections First word Names of void methods should start with a verb (e.g. GetHashCode) Other names should start with a noun (e.g. size, IndexOf, Collections) Enumeration constants or bool members may start with an adjective (Red, Empty)

Comments Single-line comments // a comment Delimited comments /* a comment */ must not be nested Documentation comments /// a documentation comment

TYPES University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

Uniform Type System Types Value Types Reference Types Pointers Simple Types Enums Structs Classes Interfaces Arrays Delegates bool char sbyte short int long byte ushort uint ulong float double decimal User-defined Types blue types are missing from Java All types are compatible with object - can be assigned to variables of type object - all operations of type object are applicable to them

Value Types and Reference Types Value Types Reference Types variable contains value reference stored on stack heap initialisation 0, false, '\0' null assignment copies the value copies the reference example int i = 17; string s = "Hello"; int j = i; string s1 = s; i 17 s H e l l o j 17 s1

Primitive Types long form in Java range sbyte System.SByte byte -128.. 127 byte System.Byte --- 0.. 255 short System.Int16 short -32768.. 32767 ushort System.UInt16 --- 0.. 65535 int System.Int32 int -2 31.. 2 31-1 uint System.UInt32 --- 0.. 2 32-1 long System.Int64 long -2 63.. 2 63-1 ulong System.UInt64 --- 0.. 2 64-1 float System.Single float 1.5E-45.. 3.4E38 (32 Bit) double System.Double double 5E-324.. 1.7E308 (64 Bit) decimal System.Decimal --- 1E-28.. 7.9E28 (128 Bit) bool System.Boolean boolean true, false char System.Char char Unicode character

Compatibility Between Primitive Types decimal double float long int short sbyte only with type cast ulong uint ushort byte char The following assignments are legal intvar = shortvar; intvar = charvar; floatvar = charvar; decimalvar = (decimal)doublevar;

Arrays One-dimensional arrays int[] a = new int[3]; int[] b = new int[] {3, 4, 5; int[] c = {3, 4, 5; SomeClass[] d = new SomeClass[10]; SomeStruct[] e = new SomeStruct[10]; // array of references // array of values (directly in the array) Multidimensional arrays (jagged) int[][] a = new int[2][]; a[0] = new int[] {1, 2, 3; a[1] = new int[] {4, 5, 6; // array of references to other arrays // cannot be initialized directly Multidimensional arrays (rectangular) int[,] a = new int[2, 3]; int[,] b = {{1, 2, 3, {4, 5, 6; int[,,] c = new int[2, 4, 2]; // block matrix // can be initialized directly

Class System.String Can be used as the standard type string string s = "Alfonso"; Note Strings are immutable (use StringBuilder if you want to modify strings) Can be concatenated with +: "Don " + s Can be indexed: s[i] String length: s.length Strings are reference types => reference semantics in assignments but their values can be compared with == and!= : if (s == "Alfonso")... Class String defines many useful operations: CompareTo, IndexOf, StartsWith, Substring,...

Variable-length Arrays using System; using System.Collections; class Test { static void Main() { ArrayList a = new ArrayList(); a.add("charly"); a.add("delta"); a.add("alpha"); a.sort(); for (int i = 0; i < a.count; i++) Console.WriteLine(a[i]); Output Alpha Charly Delta

Associative Arrays using System; using System.Collections; class Test { static void Main() { Hashtable phone = new Hashtable(); phone["karin"] = 7131; phone["peter"] = 7130; phone["wolfgang"] = 7132; foreach (DictionaryEntry x in phone) Console.WriteLine("{0 = {1", x.key, x.value); Output Karin = 7131 Peter = 7130 Wolfgang = 7132

Structs Declaration struct Point { public int x, y; public Point (int x, int y) { this.x = x; this.y = y; public void MoveTo (int a, int b) { x = a; y = b; // fields // constructor // methods Usage Point p; Point p = new Point(3, 4); p.x = 1; p.y = 2; p.moveto(10, 20); Point q = p; // still unititialized // constructor initializes object on the stack // field access // method call // value assignment of objects (all fields are assigned) Note Structs are value types! A struct declaration allocates an object directly on the stack or within some other object. Structs must not declare a parameterless constructor (they have one by default). However, they may use it: p = new Point(); // initializes fields to 0, null, false,...

Classes Declaration Usage Note class Rectangle { Point origin; public int width, height; public Rectangle() { origin = new Point(0,0); width = height = 0; public Rectangle (Point p, int w, int h) { origin = p; width = w; height = h; public void MoveTo (Point p) { origin = p; Rectangle r = new Rectangle(new Point(10, 20), 5, 5); int area = r.width * r.height; r.moveto(new Point(3, 3)); Rectangle r1 = r ; // reference assignment Classes are reference types; Their objects are allocated on the heap. The "new" operator allocates and object and calls its constructor. Classes may declare a parameterless constructor.

Differences Between Classes and Structs Classes Reference types (objects are allocated on the heap) support inheritance (all classes are derived from object) can implement interfaces may declare a parameter less constructor may have a destructor Structs Value types (objects are allocated on the stack) no inheritance (but they are compatible with object) can implement interfaces must not declare a parameter less constructor no destructors

DECLARATIONS University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

Declaration Space The program area to which a declaration belongs Kinds of declaration spaces - namespace: declarations of classes, interfaces, structs, enums, delegates - class, interface, struct: declaraions of fields, methods,... - enumeration: declarations of enumeration constants - block: declarations of local variables namespace N {... class C {... void Foo() {... if (...) {... Statement blocks are not declaration spaces on their own but belong to the declaration space of the enclosing method block

Using Other Namespaces Foreign namespaces must either be imported (e.g. using Util;) or specified in a qualified name (e.g. Util.Color) Most programs need the namespace System => using System; Color.cs Figures.cs Triangle.cs namespace Util { public enum Color {... using Util.Figures; namespace Util.Figures { public class Rect {... public class Circle {... namespace Util.Figures { public class Triangle {... class Test { Rect r; // without qualification (because of using Util.Figures) Triangle t; Util.Color c; // with qualification

CLASSES AND STRUCTS University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

Contents of Classes and Structs class C {... fields, constants... // for object-oriented programming... methods...... constructors, destructors...... properties... // for component-based programming... events...... indexers... // for amenity... overloaded operators...... nested types (classes, interfaces, structs, enums, delegates)...

Classes class Stack { int[] values; int top = 0; public Stack(int size) {... public void Push (int x) {... public int Pop() {... Objects are allocated on the heap (classes are reference types) Objects must be created with new Stack s = new Stack(100); Classes can inherit from one other class (single code inheritance) Classes can implement multiple interfaces (multiple type inheritance)

Structs struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; public MoveTo (int x, int y) {... Objects are allocated on the stack not on the heap (structs are value types) + efficient, low memory consumption, no burden for the garbage collector. - live only as long as their container (not suitable for dynamic data structures) Can be allocated with new Point p; // fields of p are not yet initialized Point q = new Point(); Fields must not be initialized at their declaration struct Point { int x = 0; // compilation error Parameter less constructors cannot be declared Can neither inherit nor be inherited, but can implement interfaces

Visibility Modifiers (excerpt) public private visible where the declaring namespace is known - Members of interfaces and enumerations are public by default. - Types in a namespace (classes, structs, interfaces, enums, delegates) have default visibility internal (visible in the declaring assembly) only visible in declaring class or struct - Members of classes and structs are private by default (fields, methods, properties,..., nested types) Example public class Stack { private int[] val; // private is also default private int top; // private is also default public Stack() {... public void Push(int x) {... public int Pop() {...

Fields and Constants class C { int value = 0; Field - initialization is optional - initialization value must be computable at compile time - fields of a struct must not be initialized const long size = ((long)int.maxvalue + 1) / 4; Constant - must be initialized - value must be computable at compile time readonly DateTime date; Read-only field - must be initialized in their declaration or in a constructor - value needs not be computable at compile time - value must not be changed later - consumes a memory location (like a field) Access within C Access from other classes... value... size... date... C c = new C();... c.value... c.size... c.date...

Static Fields and Constants Belong to a class, not to an object class Rectangle { static Color defaultcolor; // once per class static readonly int scale; // -- " -- int x, y, width,height; // once per object... Access within the class Access from other classes... defaultcolor... scale...... Rectangle.defaultColor... Rectangle.scale... Constants must not be declared static

Static Methods Operations on class data (static fields) class Rectangle { static Color defaultcolor; public static void ResetColor() { defaultcolor = Color.white; Access from Rectangle ResetColor(); Access from other classes Rectangle.ResetColor();

Parameters value parameters (input parameters) void Inc(int x) {x = x + 1; void f() { int val = 3; Inc(val); // val == 3 ref parameters (transient parameters) void Inc(ref int x) { x = x + 1; void f() { int val = 3; Inc(ref val); // val == 4 - "call by value" - formal parameter is a copy of the actual parameter - actual parameter is an expression - "call by reference" - formal parameter is an alias for the actual parameter (address of actual parameter is passed) - actual parameter must be a variable out parameters (output parameters) void Read (out int first, out int next) { first = Console.Read(); next = Console.Read(); void f() { int first, next; Read(out first, out next); - similar to ref parameters but no value is passed by the caller. - must not be used in the method before it got a value.

Variable Number of Parameters Last n parameters may be a sequence of values of a certain type. keyword params array type Usage void Add (out int sum, params int[] val) { sum = 0; foreach (int i in val) sum = sum + i; params cannot be used for ref and out parameters Add(out sum, 3, 5, 2, 9); // sum == 19 Another example void Console.WriteLine (string format, params object[] arg) {...

Method Overloading Methods of a class may have the same name - if they have different numbers of parameters, or - if they have different parameter types, or - if they have different parameter kinds (value, ref/out) Examples void F (int x) {... void F (char x) {... void F (int x, long y) {... void F (long x, int y) {... void F (ref int x) {... Calls int i; long n; short s; F(i); // F(int x) F('a'); // F(char x) F(i, n); // F(int x, long y) F(n, s); // F(long x, int y); F(i, s); // ambiguous between F(int x, long y) and F(long x, int y); => compilation error F(i, i); // ambiguous between F(int x, long y) and F(long x, int y); => compilation error Overloaded methods must not differ only in their function types, in the presence of params or in ref versus out!

Constructors for Classes Example class Rectangle { int x, y, width, height; public Rectangle (int x, int y, int w, int h) {this.x = x; this.y = y; width = x; height = h; public Rectangle (int w, int h) : this(0, 0, w, h) { public Rectangle () : this(0, 0, 0, 0) {... Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(2, 5); Rectangle r3 = new Rectangle(2, 2, 10, 5); Constructors can be overloaded. A constructor may call another constructor with this (specified in the constructor head, not in its body as in Java!). Before a constructor is called, fields are possibly initialized.

Default Constructor If no constructor was declared in a class, the compiler generates a parameterless default constructor : class C { int x; C c = new C(); // ok default constructor initializes all fields as follows: numeric 0 enumeration 0 bool false char '\0' reference null If a constructor was declared, no default constructor is generated : class C { int x; public C(int y) { x = y; C c1 = new C(); // compilation error C c2 = new C(3); // ok

Constructor for Structs Example struct Complex { double re, im; public Complex(double re, double im) { this.re = re; this.im = im; public Complex(double re) : this(re, 0) {... Complex c0; // c0.re and c0.im uninitialized Complex c1 = new Complex(); // c1.re == 0, c1.im == 0 Complex c2 = new Complex(5); // c2.re == 5, c2.im == 0 Complex c3 = new Complex(10, 3); // c3.re == 10, c3.im == 3 For every struct the compiler generates a parameterless default constructor (even if there are other constructors). The default constructor zeroes all fields. Programmers must not declare a parameterless constructor for structs (for implementation reasons of the CLR). A constructor of a struct must initialize all fields.

Static Constructors Both for classes and for structs class Rectangle {... static Rectangle() { Console.WriteLine("Rectangle initialized"); struct Point {... static Point() { Console.WriteLine("Point initialized"); Must be parameterless (also for structs) and have no public or private modifier. There must be just one static constructor per class/struct. Is invoked once before this type is used for the first time. Used for initialization of static fields.

Destructors class Test { ~Test() {... cleanup actions... Correspond to finalizers in Java. Called for an object before it is removed by the garbage collector. Can be used, for example, to close open files. Base class destructor is called automatically at the end. No public or private. Is dangerous (object resurrection) and should be avoided Structs must not have a destructor (reason unknown).

Properties Syntactic sugar for get/set methods class Data { FileStream s; property type property name public string FileName { set { s = new FileStream(value, FileMode.Create); get { return s.name; "input parameter" of the set method Used as "smart fields" Data d = new Data(); d.filename = "myfile.txt"; string s = d.filename; // calls set("myfile.txt") // calls get() JIT compilers often inline get/set methods no efficiency penalty.

Properties (continued) Assignment operators work also on properties class C { private static int size; public static int Size { get { return size; set { size = value; C.Size = 3; C.Size += 2; // Size = Size + 2;

Properties (continued) get or set can be omitted class Account { long balance; public long Balance { get { return balance; x = account.balance; account.balance =...; // ok // illegal Why are properties a good idea? Allow read-only and write-only fields. Can validate a field when it is accessed. Interface and implementation of data can differ. Substitute for fields in interfaces.

Indexers Programmable operator for indexing a collection class File { FileStream s; Usage public int this [int index] { get { s.seek(index, SeekOrigin.Begin); return s.readbyte(); set { s.seek(index, SeekOrigin.Begin); s.writebyte((byte)value); File f =...; int x = f[10]; f[10] = 'A'; type of the indexed expression // calls f.get(10) // calls f.set(10, 'A') name (always this) type and name of the index value get or set method can be omitted (write-only / read-only) indexers can be overloaded with different index type.net library has indexers for string (s[i]), ArrayList (a[i]), etc.

Conversion Operators Implicit conversion - If the conversion is always possible without loss of precision - e.g. long = int; Explicit conversion - If a run time check is necessary or truncation is possible - e.g. int = (int) long; Conversion operators for user-defined types Usage class Fraction { int x, y;... public static implicit operator Fraction (int x) { return new Fraction(x, 1); public static explicit operator int (Fraction f) { return f.x / f.y; Fraction f = 3; // implicit conversion, f.x == 3, f.y == 1 int i = (int) f; // explicit conversion, i == 3

Nested Types class A { private int x; B b; public void Foo() { b.bar();... public class B { A a; public void Bar() { a.x =...;... a.foo();... class C { A a = new A(); A.B b = new A.B(); For auxiliary classes that should be hidden - Inner class can access all members of the outer class (even private members). - Outer class can access only public members of the inner class. - Other classes can access an inner class only if it is public. Nested types can also be structs, enums, interfaces and delegates.

INHERITANCE University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

Syntax class A { int a; public A() {... public void F() {... // base class class B : A { // subclass (inherits from A, extends A) int b; public B() {... public void G() {... B inherits a and F(), it adds b and G() - constructors are not inherited - inherited methods can be overridden (see later) Single inheritance: a class can only inherit from one base class, but it can implement multiple interfaces. A class can only inherit from a class, not from a struct. Structs cannot inherit from another type, but they can implement multiple interfaces. A class without explicit base class inherits from object.

Assignments and Type Checks class A {... class B : A {... class C: B {... Assignments A a = new A(); // static type of a: the type specified in the declaration (here A) // dynamic type of a: the type of the object in a (here also A) a = new B(); // dynamic type of a is B a = new C(); // dynamic type of a is C B b = a; // forbidden; compilation error Run-time type checks a = new C(); if (a is C)... // true, if the dynamic type of a is C or a subclass; otherwise false if (a is B)... // true if (a is A)... // true, but warning because it makes no sense a = null; if (a is C)... // false: if a == null, a is T always returns false

Checked Type Casts Cast A a = new C(); B b = (B) a; C c = (C) a; a = null; c = (C) a; // if (a is B) stat.type(a) is B in this expression; else exception // ok null can be casted to any reference type as A a = new C(); B b = a as B; C c = a as C; a = null; c = a as C; // if (a is B) b = (B)a; else b = null; // c == null

Overriding Methods Only methods that are declared as virtual can be overridden in subclasses class A { public void F() {... // cannot be overridden public virtual void G() {... // can be overridden in a subclass Overriding methods must be declared as override class B : A { public void F() {... // warning: hides inherited F() use new public void G() {... // warning: hides inherited G() use new public override void G() { // ok: overrides inherited G... base.g(); // calls inherited G() Method signatures must be identical - same number and types of parameters (including function type) - same visibility (public, protected,...). Properties and indexers can also be overridden (virtual, override). Static methods cannot be overridden.

Hiding Members can be declared as new in a subclass. They hide inherited members with the same name and signature. class A { public int x; public void F() {... public virtual void G() {... class B : A { public new int x; public new void F() {... public new void G() {... B b = new B(); b.x =...; b.f();... b.g(); ((A)b).x =...; ((A)b).F();... ((A)b).G(); // accesses B.x // calls B.F and B.G // accesses A.x! // calls A.F and A.G!

Visibility protected and internal Protected Visible in the declaring class and its subclasses (more restricive than in Java) Visible in the declaring assembly (see later) internal protected internal Visible in declaring class, its subclasses and the declaring assembly Example class Stack { protected int[] values = new int[32]; protected int top = -1; public void Push(int x) {... public int Pop() {... class BetterStack : Stack { public bool Contains(int x) { foreach (int y in values) if (x == y) return true; return false; class Client { Stack s = new Stack();... s.values[0]... // illegal: compilation error

Abstract Classes Example abstract class Stream { public abstract void Write(char ch); public void WriteString(string s) { foreach (char ch in s) Write(s); class File : Stream { public override void Write(char ch) {... write ch to disk... Note Abstract methods do not have an implementation. Abstract methods are implicitly virtual. If a class has abstract methods (declared or inherited) it must be abstract itself. One cannot create objects of an abstract class..

Abstract Properties and Indexers Example abstract class Sequence { public abstract void Add(object x); public abstract string Name { get; public abstract object this [int i] { get; set; // method // property // indexer class List : Sequence { public override void Add(object x) {... public override string Name { get {... public override object this [int i] { get {... set {... Note Overridden indexers and properties must have the same get and set methods as in the base class

Example sealed class Account : Asset { long val; public void Deposit (long x) {... public void Withdraw (long x) {...... Note sealed classes cannot be extended (same as final classes in Java), but they can inherit from other classes. override methods can be declared as sealed individually. Reason: Security (avoids inadvertent modification of the class semantics) Efficiency (methods can possibly be called using static binding)

Class System.Object Topmost base class of all other classes class Object { protected object MemberwiseClone() {... public Type GetType() {... public virtual bool Equals (object o) {... public virtual string ToString() {... public virtual int GetHashCode() {... Directly usable: Type t = x.gettype(); object copy = x.memberwiseclone(); is protected!) returns a type descriptor (for reflection) does a shallow copy (this method Overridable in subclasses: x.equals(y) x.tostring() int code = x.gethashcode(); should compare the values of x and y should return a string representation of x should return a hash code for x

Example (for using object) class Fraction { int x, y; public Fraction(int x, int y) { this.x = x; this.y = y;... public override string ToString() { return String.Format("{0/{1", x, y); public override bool Equals(object o) { Fraction f = (Fraction)o; return f.x == x && f.y == y; public override int GetHashCode() { return x ^ y; public Fraction ShallowCopy() { return (Fraction) MemberwiseClone(); class Client { static void Main() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(1, 2); Fraction c = new Fraction(3, 4); Console.WriteLine(a.ToString()); // 1/2 Console.WriteLine(a); // 1/2 (ToString is called automatically) Console.WriteLine(a.Equals(b)); Console.WriteLine(a == b); Console.WriteLine(a.GetHashCode()); // 3 // true // false a = c.shallowcopy(); Console.WriteLine(a); // 3/4

Example (for overloading == and!=) class Fraction { int x, y; public Fraction(int x, int y) { this.x = x; this.y = y;... public static bool operator == (Fraction a, Fraction b) { return a.x == b.x && a.y == b.y; public static bool operator!= (Fraction a, Fraction b) { return! (a == b); class Client { static void Main() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(1, 2); Fraction c = new Fraction(3, 4); Console.WriteLine(a == b); // true Console.WriteLine((object)a == (object)b); // false Console.WriteLine(a.Equals(b)); // true, because overridden in Fraction If == is overloaded,!= must be overloaded as well. Compiler prints a warning if == and!= are overloaded, but Equals is not overridden.

New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

GENERIC TYPES

Problems Without Generic Types Assume we need a class that can work with arbitrary objects class Buffer { private object[] data; public void Put(object x) {... public object Get() {... Problems Type casts needed buffer.put(3); int x = (int)buffer.get(); // boxing imposes run-time costs // type cast imposes run-time costs One cannot statically enforce homogeneous data structures buffer.put(3); buffer.put(new Rectangle()); Rectangle r = (Rectangle)buffer.Get(); // can result in a run-time error! Special types IntBuffer, RectangleBuffer,... introduce redundancy

Generic Class Buffer generic type placeholder type class Buffer<Element> { private Element[] data; public Buffer(int size) {... public void Put(Element x) {... public Element Get() {... works also for structs and interfaces placeholder type Element can be used like a normal type Usage Buffer<int> a = new Buffer<int>(100); a.put(3); // accepts only int parameters; no boxing int i = a.get(); // no type cast needed! Buffer<Rectangle> b = new Buffer<Rectangle>(100); b.put(new Rectangle()); // accepts only Rectangle parameters Rectangle r = b.get(); // no typ cast needed! Benefits homogeneous data structure with compile-time type checking efficient (no boxing, no type casts) Genericity is also available in Ada, Eiffel, C++ (templates), Java 1.5

Multiple Placeholder Types Buffer with priorities class Buffer <Element, Priority> { private Element[] data; private Priority[] prio; public void Put(Element x, Priority prio) {... public void Get(out Element x, out Priority prio) {... Usage Buffer<int, int> a = new Buffer<int, int>(); a.put(100, 0); int elem, prio; a.get(out elem, out prio); Buffer<Rectangle, double> b = new Buffer<Rectangle, double>(); b.put(new Rectangle(), 0.5); Rectangle r; double prio; b.get(out r, out prio); C++ allows also placeholders for constants, C# does not

Constraints Constraints about placeholder types are specified as base types class OrderedBuffer <Element, Priority> where Priority: IComparable { Element[] data; Priority[] prio; int lastelem;... public void Put(Element x, Priority p) { int i = lastelement; while (i >= 0 && p.compareto(prio[i]) > 0) {data[i+1] = data[i]; prio[i+1] = prio[i]; i--; data[i+1] = x; prio[i+1] = p; Allows operations on instances of placeholder types interface or base class Usage OrderedBuffer<int, int> a = new OrderedBuffer<int, int>(); a.put(100, 3); parameter must implement IComparable

Multiple Constraints class OrderedBuffer <Element, Priority> where Element: MyClass where Priority: IComparable where Priority: ISerializable {... public void Put(Element x, Priority p) {... public void Get(out Element x, out Priority p) {... Usage must be a subclass of MyClass must implement IComparable and ISerializable OrderedBuffer<MySubclass, MyPrio> a = new OrderedBuffer<MySubclass, MyPrio>();... a.put(new MySubclass(), new MyPrio(100));

Constructor Constraint For creating objects of a generic types class Stack<T, E> where E: Exception, new() { T[] data =...; int top = -1; public void Push(T x) { if (top >= data.length) throw new E(); else data[++top] = x; specifies that the placeholder E must have a parameterless constructor. Usage class MyException: Exception { public MyException(): base("stack overflow or underflow") { Stack<int, MyException> stack = new Stack<int, MyException>();... stack.push(3);

Genericity and Inheritance class Buffer <Element>: List<Element> {... public void Put(Element x) { this.add(x); // Add is inherited from List can also implement generic interfaces From which classes may a generic class be derived? from a non-generic class class T<X>: B {... from an instantiated generic class class T<X>: B<int> {... from a generic class class T<X>: B<X> {... with the same placeholder

Methoden that can work with arbitrary data types Generic Methods static void Sort<T> (T[] a) where T: IComparable { for (int i = 0; i < a.length-1; i++) { for (int j = i+1; j < a.length; j++) { if (a[j].compareto(a[i]) < 0) { T x = a[i]; a[i] = a[j]; a[j] = x; can sort any array as long as the array elements implement IComparable Usage int[] a = {3, 7, 2, 5, 3;... Sort<int>(a); // a == {2, 3, 3, 5, 7 string[] s = {"one", "two", "three";... Sort<string>(s); // s == {"one", "three", "two" From the method parameters the compiler can usually infer the concrete type that is to be substituted for the placeholder type; so one can simply write: Sort(a); // a == {2, 3, 3, 5, 7 Sort(s); // s == {"one", "three", "two"

Null Values Setting a value to null void Foo<T>() { T x = null; T y = 0; T z = T.default; // error // error // ok! 0, '\0', false, null Comparing a value against null void Foo<T>(T x) { if (x == null) { Console.WriteLine(true); else { Console.WriteLine(false"); for reference types x == null does a comparison for value types x == null returns false Foo(3); Foo(0); Foo("Hello"); Foo<string>(null); // false // false // false // true

Namespace System.Collections.Generic New generic types Classes List<T> Dictionary<T, U> SortedDictionary<T, U> Stack<T> Queue<T> corresponds to ArrayList corresponds to Hashtable There is no SortedList<T> However, List<T> can be sorted with the Sort method Interfaces ICollection<T> IList<T> IDictionary<T, U> IEnumerable<T> IEnumerator<T> IComparable<T> IComparer<T>

ITERATORS

Iterators so far foreach loop can be applied to objects of classes which implement IEnumerable class MyClass: IEnumerable {... public IEnumerator GetEnumerator() { return new MyEnumerator(...); interface IEnumerable { IEnumerator GetEnumerator(); class MyEnumerator: IEnumerator { public object Current { get {... public bool MoveNext() {... public void Reset() {... MyClass x = new MyClass();... foreach (object obj in x)... complicated to implement!!

Iterator Methods class MyClass { string first = "first"; string second = "second"; string third = "third";... public IEnumerator GetEnumerator() { yield return first; yield return second; yield return third; Characteristics of an interator method 1. has the signature public IEnumerator GetEnumerator 2. statement body contains at least one yield statement MyClass x = new MyClass();... foreach (string s in x) Console.Write(s + " "); // liefert "first second third" How does an iterator method work? 1. returns a sequence of values 2. foreach loop traverses this sequence Note MyClass need not implement IEnumerable! Instead of IEnumerator it is better to use IEnumerator<string> (avoids a type cast) IEnumerator<T> is in System.Collections.Generic

What Happens Behind the Scene? returns an object of the following class public IEnumerator<int> GetEnumerator() { try {... finally {... class _Enumerator : IEnumerator<int> { int Current { get {... bool MoveNext() {... void Dispose() {... is translated into foreach (int x in list) Console.WriteLine(x); IEnumerator<int> _e = list.getenumerator(); try { while (_e.movenext()) Console.WriteLine(_e.Current); finally { if (_e!= null) _e.dispose(); MoveNext runs to the next yield statement Dispose executes a possibly existing finally block in the iterator method

yield Statement 2 kinds yield return expr; yields a value for the foreach loop may only occur in an iterator method type of expr must be compatible with - T (if IEnumerator<T>) - object (otherwise) yield break; terminates the iteration may only occur in an iterator method

Example: Iterating Over a Tree class Tree { Node root = null; public void Add(int val) {... public bool Contains(int val) {... public IEnumerator<int> GetEnumerator() { return root.getenumerator(); class Node { public int val; public Node left, right; public Node(int x) { val = x; Usage... Tree tree = new Tree();... foreach (int x in tree) Console.WriteLine(x); public IEnumerator<int> GetEnumerator() { if (left!= null) foreach (int x in left) yield return x; yield return val; if (right!= null) foreach (int x in right) yield return x; Creates an enumerator object for every node of the tree!

ANONYMOUS METHODS

Ordinary Delegates delegate void Visitor(Node p); class List { Node[] data =...;... public void ForAll(Visitor visit) { for (int i = 0; i < data.length; i++) visit(data[i]); class C { int sum = 0; void SumUp(Node p) { sum += p.value; void Print(Node p) { Console.WriteLine(p.value); void Foo() { List list = new List(); list.forall(sumup); list.forall(print); requires the declaration of a named method (SumUp, Print,...) SumUp and Print cannot access the local variables of Foo => sum must be declared as a global field

Anonymous Methods delegate void Visitor(Node p); class C { void Foo() { List list = new List(); int sum = 0; list.forall(delegate (Node p) { Console.WriteLine(p.value); ); list.forall(delegate (Node p) { sum += p.value; ); formal parameter code class List {... public void ForAll(Visitor visit) {... method code is specified in-place does not require the declaration of a named method anonymous method can access Foo's local variable sum return terminates the anonymous method (not the enclosing method) Restrictions anonymous methods must not have formal parameters of the kind params T[] anonymous methods must not be assigned to object anonymous methods must not access ref or out parameters of the enclosing method

Further Simplification delegate void EventHandler (object sender, EventArgs arg); Button button = new Button(); Button.Click += delegate (object sender, EventArgs arg) { Console.WriteLine("clicked"); ; Can be simplified as follows Button.Click += delegate { Console.WriteLine("clicked"); ; Formal parameters can be omitted if they are not used in the method body Restriction Formal parameters can only be omitted if the delegate type does not have out parameters

PARTIAL TYPES

Class Consisting of Multiple Parts public partial class C { int x; public void M1(...) {... public int M2(...) {... public partial class C { string y; public void M3(...) {... public void M4(...) {... public void M5(...) {... file Part1.cs file Part2.cs Benefit Parts can be grouped by functionality different developers can work on different parts of the class at the same time one part can be machine-generated, other parts can be hand-written Should only be used as an exception

VARIOUS

Static Classes May only have static fields and methods static class Math { public static double Sin(double x) {... public static double Cos(double x) {...... Benefit shows explicitly that this class contains only static members the compiler can make sure that all members are declared as static Static classes must not be used as types

The Evolution of C# C# 2.0 C# 3.0 Generics Local variable type inference, Lambda expressions, Object instantiation, Anonymous types, Extension methods C# 1.0 Components on a Managed Runtime

Work Citied Mössenböck, H., Beer, W., Prähofer, H., & Wöß, A. (09.02.2007). Application Development with C# and.net. Retrieved March 06, 2008, from http://dotnet.jku.at/courses/dotnet/