java2c# antonio cisternino part ii. outline array types enum types value types differences from...

39
Java2C# Antonio Cisternino Part II

Upload: tracey-rice

Post on 29-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

Java2C#

Antonio Cisternino

Part II

Outline

Array types Enum types Value types

differences from classes boxing and unboxing

Delegate types Base structure Multicast delegates Event model using delegates

Event type

Outline

Array types Enum types Value types

differences from classes boxing and unboxing

Delegate types Base structure Multicast delegates Event model using delegates

Event type

Arrays

C# provides several kind of arrays:Single dimensionalMultidimensionalJagged

Arrays can also be specified as in/out A method could fill the content of an array Arrays derive from System.Array class

Array initialization

Empty arrays are created as follows:int[] a = new int[10];

Empty arrays are initialized with empty values or null for non-value types

C# provides the following syntax to initialize an array:string[] a = {"a","b","c"};a = new string{"a","b","d"};

Multidimensional arrays

C# allows defining n-dimensional arrays:int[,,] a = new int[2, 3, 4];

Initializers can be defined as before:int[,] a = {{1, 2}, {1,2}};int[,] a = new int[,]{{1,2},{1,2}};

Multidimensional arrays are more efficient than arrays of arrays although Jagged arrays may save memory

Jagged arrays

Arrays of arrays are called jagged:int[][] a = new int[3][];a[0] = new int[5];a[1] = new int[3];a[2] = new int[0];

In this case the rank of the array is not defined because rows can contain array of different size

Passing arrays as arguments

Array can be passed using out and ref. For instance:void Fill(out int[] a) {

a = new int[]{1,2,3};

}

int[] a;

Fill(out a);

Outline

Array types

Enum types Value types

differences from classes boxing and unboxing

Delegate types Base structure Multicast delegates Event model using delegates

Event type

Enumeration types

Nearly C++ enumeration, but more expressive Example:

enum AccessMode {

Read, Write, Execute }; By default enumeration are equivalent to integer Each label is associated with a value; if

unspecified the previous value incremented by 1 Enumeration values start from 0 (if unspecified)

Controlling values

Enumerations are used to define set of semantically related integral constants

Example:enum AccessMode { Read = 0x01, Write = 0x02, Execute = 0x04}

Values can be used to form bit-masks

Specifying enumeration type

Enumeration may be derived from: byte, sbyte, short, ushort, int, uint, long or ulong

Example:enum Foo : byte { A = -1, // Error! B = 2, C}

The following operators can be used on enumerated values: ==, !=, <, >, <=, >=, +, -, ^, &, |, ~, ++, --, sizeof

Enumeration are types! Explicit cast are needed to cast to the type from which derive

Outline

Array types Enum types

Value types differences from classes boxing and unboxing

Delegate types Base structure Multicast delegates Event model using delegates

Event type

Memory management

Traditionally allocation of data structures could be static; automatic or dynamic

Static allocation consists in memory areas allocated during program loading

Automatic allocation allocates room for local variables on the stack

Dynamic allocation makes use of a memory area called heap handled by language runtime

How do I allocate my data?

Allocation models have costs distributed over: Allocation Effective use (memory is finite) Free

Programs use memory (either directly or indirectly) and its use influences performance: Static allocation is efficient but not flexible Automatic allocation is related to a method invocation

and not under program control Dynamic allocation is optimal in terms of allocation

but is expensive

Values and objects

C# and CLR distinguish between values and objects

Values are usually allocated on the stack (automatic) and are copied by default during method call

Besides objects are allocated on the heap and their lifetime is controlled by the garbage collector

Values and objects

Values have an associated type inherited from System.ValueType

Although they appear to be objects this is not true because identity is not preserved

A special technique called boxing is used to treat a value as an object only if needed

Values are helpful to reduce overhead in memory allocation when identity is not required

Example

using System;

namespace Foo {struct Complex { public double re; public double im;}public class MainClass { public static void Main(string[]

args) { Complex c = new Complex(); c.re = 1; c.im = 0;

Console.WriteLine( "c before boxing is {0} + {1}i", c.re, c.im); object o = c; // BOXING c.re = 2; Console.WriteLine( "c is {0} + {1}i", c.re, c.im); c = (Complex)o; // UNBOXING Console.WriteLine("unboxed c is

{0} + {1}i", c.re, c.im); }}}

Output

How do you explain the following output?C:\> vtc before boxing is 1 + 0ic is 2 + 0iunboxed c is 1 + 0iC:\> _

The value is copied into an object on the heap and then copied back

Value Types

A value type is similar to a class: allow definition of methods, properties and operators

Inheritance is not allowed because values cannot support the same structure of objects

Empty constructor cannot be overridden! Value types are useful when

automatic allocation is appropriate the overhead of copy is less than overhead of GC

Looks very like classes! Examples: complex numbers, pairs, points, …

Outline

Array types Enum types Value types

differences from classes boxing and unboxing

Delegate types Base structure Multicast delegates Event model using delegates

Event type

Delegate types

A delegate is a type that describes a class of methods Example:

class Foo { delegate int MyFun(int i, int j); static int Add(int i, int j) { return i + j; } static void Main(string[] args) { MyFun f = new MyFun(Foo.Add); Console.WriteLine(f(2, 3)); }}

Is it a function pointer?

NOOOOOOOOOOOOOOOOOOOOOOOO A delegate is more than a pointer! It is a special

object To understand what a delegate really is try to

answer to: “How a delegate can invoke an instance method?”

An instance method must be invoked on an object! We may use a pair (object, method)

CLR delegates

Object

Method

Delegate object

Object

Method code

Delegates as types

A delegate type allows building delegate objects on methods with a specified signature

The type exposes an Invoke method with the appropriate signature at CLR level

C# exposes delegates with a special syntax in the declaration (not class like)

The pair is built using the new operator and the pair is specified using an invocation-like syntax

Delegates like closures?

In functional programming it is possible to define a function that refers external variables

The behavior of the function depends on those external values and may change

Closures are used in functional programming to close open terms in functions

Delegates are not equivalent to closures although are a pair (env, func): the environment should be of the same type to which the method belongs

Functional programming in C#?

Delegates allow representing static and instance methods as values

Those values can be passed over the stack to methods

In some sense methods become first class values: the program can manipulate them

Great implications: introduction of FP elements in the mainstream, cleaner event model (call-backs can be naturally expressed as delegates)

Example: Aggregate function

The following method maps a function on an array:delegate int MyFun(int);int[] ApplyInt(MyFun f, int[] a) { int[] r = new int[a.Length]; for (int i = 0;i < a.Length;i++) r[i] = f(a[i]); return r;}

Events using delegates?

Event system are built on the notion of notification (call-back)

A method invocation can be seen as a notification

In graphic frameworks such as OWL, MFC, Java 1.0.2 were made using virtual methods

Java 1.1 introduces delegation event model: There are source of events There are listeners that ask sources for notifications Event fires: a method is invoked for all subscribers

Delegation Event Model

Event Source

SubscriberSubscribe

Notification

Subscribed listeners

Delegate event model in Java

Which method should call the event source to notify the event?

In Java there are no delegates and interfaces are used instead (XXXListener)

The listener should implement an interface and the source implements a method for (un)subscription.

A vector of subscribed listeners is kept by the event source

Delegates to handle events

Delegates allows connecting event sources to listeners from outside the involved types

In C# we can use a delegate object to specify which method should be invoked when an event is notified

A first approach could be using an array of delegates into source to represents subscribers

Some component (not necessarily the listener) builds a delegate on the listener and performs subscription

Multicast delegates

Event notification is in general one-to-many CLR provides multicast delegates to support

notification to many listeners A multicast delegate is a kind of delegate that

holds inside a list of ‘delegate objects’ Multicast delegates keep track of subscriptions

to event sources reducing the burden of replicating the code

Multicast delegates: Example

delegate void Event();class EventSource { public Event evt; // … evt(); // fires the event // …}

class Foo { public void MyMethod() {} }

// Some code somewhere!EventSource src = new EventSource();Foo f = new Foo();src.evt += new Event(f.MyMethod);

Unrelated types!

C# and delegates

In C# there is no way to choose between single and multicast delegates

The compiler always generates multicast delegates

In principle JIT could get rid off possible inefficiencies

Introduction of delegates will have the same impact as the introduction of interfaces in Java with respect to programming patterns

Outline

Array types Enum types Value types

differences from classes boxing and unboxing

Delegate types Base structure Multicast delegates Event model using delegates

Event type

Event keyword

C# introduces the event keyword to control access to a delegate member.

If a delegate field of a class is labeled with event then outside code will be able to use only += and -= operators on it

Listener would not be allowed to affect the subscribers list in other ways

Event infrastructures can be easily implemented by means of this keyword and delegates

Event delegates: Example

delegate void Event();class EventSource { public event Event evt; // … evt(); // fires the event // …}

class Foo { public void MyMethod() {} }

// Some code somewhere!EventSource src = new EventSource();Foo f = new Foo();src.evt += new Event(f.MyMethod);src.evt = null; // ERROR!

Next lecture

Classes virtual methods Properties Fields new names operator overloading

Reflection Custom attributes Generation of code using reflection

Statements and other new operators