html5-img
1 / 39

Java2C#

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

Download Presentation

Java2C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java2C# Antonio Cisternino Part II

  2. 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

  3. 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

  4. Arrays • C# provides several kind of arrays: • Single dimensional • Multidimensional • Jagged • Arrays can also be specified as in/out • A method could fill the content of an array • Arrays derive from System.Array class

  5. 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"};

  6. 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

  7. 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

  8. 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);

  9. 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

  10. 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)

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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); } } } Example

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

  20. 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, …

  21. 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

  22. 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)); } }

  23. 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)

  24. CLR delegates Delegate object Object Object Method Method code

  25. 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

  26. 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

  27. 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)

  28. 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; }

  29. 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

  30. Delegation Event Model Subscriber Subscribe Event Source Notification Subscribed listeners

  31. 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

  32. 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

  33. 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

  34. 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!

  35. 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

  36. 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

  37. 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

  38. 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!

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

More Related