Java 2 C Antonio Cisternino Part II Outline




![Array initialization n Empty arrays are created as follows: int[] a = new int[10]; Array initialization n Empty arrays are created as follows: int[] a = new int[10];](https://slidetodoc.com/presentation_image_h2/d861a2108d199f009526eb59a3c608d0/image-5.jpg)
![Multidimensional arrays n C# allows defining n-dimensional arrays: int[, , ] a = new Multidimensional arrays n C# allows defining n-dimensional arrays: int[, , ] a = new](https://slidetodoc.com/presentation_image_h2/d861a2108d199f009526eb59a3c608d0/image-6.jpg)
![Jagged arrays n Arrays of arrays are called jagged: int[][] a = new int[3][]; Jagged arrays n Arrays of arrays are called jagged: int[][] a = new int[3][];](https://slidetodoc.com/presentation_image_h2/d861a2108d199f009526eb59a3c608d0/image-7.jpg)
































- Slides: 39

Java 2 C# Antonio Cisternino Part II

Outline n n n Array types Enum types Value types differences from classes ¨ boxing and unboxing ¨ n Delegate types Base structure ¨ Multicast delegates ¨ Event model using delegates ¨ n Event type

Outline n Array types n Enum types Value types n differences from classes ¨ boxing and unboxing ¨ n Delegate types Base structure ¨ Multicast delegates ¨ Event model using delegates ¨ n Event type

Arrays n C# provides several kind of arrays: ¨ Single dimensional ¨ Multidimensional ¨ Jagged Arrays can also be specified as in/out n A method could fill the content of an array n Arrays derive from System. Array class n
![Array initialization n Empty arrays are created as follows int a new int10 Array initialization n Empty arrays are created as follows: int[] a = new int[10];](https://slidetodoc.com/presentation_image_h2/d861a2108d199f009526eb59a3c608d0/image-5.jpg)
Array initialization n Empty arrays are created as follows: int[] a = new int[10]; Empty arrays are initialized with empty values or null for non-value types n C# provides the following syntax to initialize an array: n string[] a = {"a", "b", "c"}; a = new string{"a", "b", "d"};
![Multidimensional arrays n C allows defining ndimensional arrays int a new Multidimensional arrays n C# allows defining n-dimensional arrays: int[, , ] a = new](https://slidetodoc.com/presentation_image_h2/d861a2108d199f009526eb59a3c608d0/image-6.jpg)
Multidimensional arrays n C# allows defining n-dimensional arrays: int[, , ] a = new int[2, 3, 4]; n Initializers can be defined as before: int[, ] a = {{1, 2}, {1, 2}}; int[, ] a = new int[, ]{{1, 2}, {1, 2}}; n Multidimensional arrays are more efficient than arrays of arrays although Jagged arrays may save memory
![Jagged arrays n Arrays of arrays are called jagged int a new int3 Jagged arrays n Arrays of arrays are called jagged: int[][] a = new int[3][];](https://slidetodoc.com/presentation_image_h2/d861a2108d199f009526eb59a3c608d0/image-7.jpg)
Jagged arrays n 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]; n In this case the rank of the array is not defined because rows can contain array of different size

Passing arrays as arguments n 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 n Array types n Enum types n Value types differences from classes ¨ boxing and unboxing ¨ n Delegate types Base structure ¨ Multicast delegates ¨ Event model using delegates ¨ n Event type

Enumeration types n n Nearly C++ enumeration, but more expressive Example: enum Access. Mode { Read, Write, Execute }; n n n 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 n n Enumerations are used to define set of semantically related integral constants Example: enum Access. Mode { Read = 0 x 01, Write = 0 x 02, Execute = 0 x 04 } n Values can be used to form bit-masks

Specifying enumeration type n n Enumeration may be derived from: byte, short, ushort, int, uint, long or ulong Example: enum Foo : byte { A = -1, // Error! B = 2, C } n n 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 n Array types Enum types n Value types n differences from classes ¨ boxing and unboxing ¨ n Delegate types Base structure ¨ Multicast delegates ¨ Event model using delegates ¨ n Event type

Memory management n n 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? n Allocation models have costs distributed over: ¨ Allocation ¨ Effective use ¨ Free n (memory is finite) 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 n Values are usually allocated on the stack (automatic) and are copied by default during method call n Besides objects are allocated on the heap and their lifetime is controlled by the garbage collector n

Values and objects n n Values have an associated type inherited from System. Value. Type 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 Main. Class { public static void Main(string[] args) { Complex c = new Complex(); c. re = 1; c. im = 0; Console. Write. Line( "c before boxing is {0} + {1}i", c. re, c. im); object o = c; // BOXING c. re = 2; Console. Write. Line( "c is {0} + {1}i", c. re, c. im); c = (Complex)o; // UNBOXING Console. Write. Line("unboxed c is {0} + {1}i", c. re, c. im); } } }

Output n How do you explain the following output? C: > vt c before boxing is 1 + 0 i c is 2 + 0 i unboxed c is 1 + 0 i C: > _ n The value is copied into an object on the heap and then copied back

Value Types n n 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 n n of GC Looks very like classes! Examples: complex numbers, pairs, points, …

Outline n n n Array types Enum types Value types differences from classes ¨ boxing and unboxing ¨ n Delegate types Base structure ¨ Multicast delegates ¨ Event model using delegates ¨ n Event type

Delegate types n n A delegate is a type that describes a class of methods Example: class Foo { delegate int My. Fun(int i, int j); static int Add(int i, int j) { return i + j; } static void Main(string[] args) { My. Fun f = new My. Fun(Foo. Add); Console. Write. Line(f(2, 3)); } }

Is it a function pointer? NOOOOOOOOOOOO n A delegate is more than a pointer! It is a special object n To understand what a delegate really is try to answer to: “How a delegate can invoke an instance method? ” n An instance method must be invoked on an object! We may use a pair (object, method)

CLR delegates Delegate object Object Method code

Delegates as types n n 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? n n 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#? n n 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 (callbacks can be naturally expressed as delegates)

Example: Aggregate function n The following method maps a function on an array: delegate int My. Fun(int); int[] Apply. Int(My. Fun 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? n n 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 Subscribe Event Source Subscribed listeners Subscriber Notification

Delegate event model in Java n n 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 n n 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 n n 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 Event. Source { public Event evt; // … evt(); // fires the event // … } Unrelated types! class Foo { public void My. Method() {} } // Some code somewhere! Event. Source src = new Event. Source(); Foo f = new Foo(); src. evt += new Event(f. My. Method);

C# and delegates n n 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 n n n Array types Enum types Value types differences from classes ¨ boxing and unboxing ¨ n Delegate types Base structure ¨ Multicast delegates ¨ Event model using delegates ¨ n Event type

Event keyword n n 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 Event. Source { public event Event evt; // … evt(); // fires the event // … } class Foo { public void My. Method() {} } // Some code somewhere! Event. Source src = new Event. Source(); Foo f = new Foo(); src. evt += new Event(f. My. Method); src. evt = null; // ERROR!

Next lecture n Classes ¨ virtual methods ¨ Properties ¨ Fields ¨ new names ¨ operator overloading n Reflection ¨ Custom attributes ¨ Generation of code n using reflection Statements and other new operators