Java2C# Antonio Cisternino Part II. Outline Array types Enum types Value types  differences from classes  boxing and unboxing Delegate types  Base.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Lecture 2 Basics of C#. Members of a Class A field is a variable of any type that is declared directly in a class. Fields are members of their containing.
Road Map Introduction to object oriented programming. Classes
Case, Arrays, and Structures. Summary Slide  Case Structure –Select Case - Numeric Value Example 1 –Select Case - String Value Example  Arrays –Declaring.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Giuseppe Attardi Antonio Cisternino
Trey Mack James Moore Osa Osar-Emokpae
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Programming in C# Language Overview
OOP Languages: Java vs C++
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Object Oriented Software Development 4. C# data types, objects and references.
Classes, Interfaces and Packages
Introduction to C# By: Abir Ghattas Michel Barakat.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Creating and Using Objects, Exceptions, Strings
Chapter 6 – Data Types CSCE 343.
Java Primer 1: Types, Classes and Operators
Module 5: Common Type System
Structs.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
Interfaces, Enumerations, Boxing, and Unboxing
Presentation 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 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

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:\> 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

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 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 Subscriber Subscribe 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