Jon Shemitz Complicated stuff, quickly..NET 2.0. ● Generics50% & Nullable Types ● Iterators 10% ● Delegate Enhancements35% ● Partial Types5%

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
 2007 Dr. Natheer Khasawneh. Chapter 13. Graphical User Interface Concepts: Part 1.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Written by: Dr. JJ Shepherd
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Generic programming in Java
Jon Shemitz Complicated stuff, quickly. Advanced Delegates.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
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++
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Iterator Pattern Dr. Neal CIS 480. Iterator An iterator pattern can be used when one class is a collection of things and would like to provide a standardized.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
Unified Modeling Language
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Copyright © 2006 Thomas P. Skinner1 Chapter 5 Indexers, Interfaces, and Enumerators.
Class Inheritance UNC-CHAPEL HILL COMP 401 BRIAN CRISTANTE 5 FEBRUARY 2015.
The Java Programming Language
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
.NET 2.0 and Visual Studio 2005 SigWin Outline Language enhancements in C# Language enhancements in C# –Generics –Partial types –Anonymous methods.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
C# Programming: From Problem Analysis to Program Design1 10 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
 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.
Introduction to C# By: Abir Ghattas Michel Barakat.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
April 20, 1998CS102-02Lecture 4-1 A Method to the Madness CS Lecture 4-1 Java's Work Horses.
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 –
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
Chapter 5: Programming with C#
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
6 Delegate and Lambda Expressions
Conditional Statements
Generics 27-Nov-18.
CIS 199 Final Review.
5. 3 Coding with Denotations
Generics 2-May-19.
Review for Midterm 3.
„Lambda expressions, Optional”
Threads and concurrency / Safety
Presentation transcript:

Jon Shemitz Complicated stuff, quickly..NET 2.0

● Generics50% & Nullable Types ● Iterators 10% ● Delegate Enhancements35% ● Partial Types5%

Generics ● Collections before generics ● Open classes ● Open methods ● Collections after generics ● Nullable types

Collections before generics Universal collections are pretty nice: – An ArrayList is a 1-D list of any object – A Hashtable can associate any object with any object But we get an object back: Always have to cast back to the type we put in. Cumbersome, and boxing is not free.

Open Classes Old style classes are now closed classes. Open classes have type parameters. A list of names in brackets between class name and {} code. List {} and Dictionary {}. A List is a closed constructed class.

Open Class Example public static class Unique where T : class, new()// can't new string() { private static T cache = default(T); private static object cacheLock = new object(); // can't lock cache field (which may be null) - // mustn't lock typeof(T) or typeof(Unique ) public static T Instance { get { lock (cacheLock) if (cache == null) return cache = new T(); else return cache; }

Open Methods Only an open class can have: A parameterized field, or a parameterized property, Or a normal method, with parameterized parameters or result Any class can have an open method: T ToType (string AsString) string ToString (T value)

Collections after generics A List compiles to generic CIL Same as Unique Yes, whatever the source language. C#, Visual Fred, Delphi... The Add method only takes a T List can't Add(int) The Get methods return a T - never has to be cast. No runtime type checking - No boxing and unboxing

Nullable Types ● bool? is the same as Nullable. bool? ThreeWay = true; // also false and null ● bool? is not the same as bool. Can't do bool TwoWay = ThreeWay; Have to do bool TwoWay = (bool) ThreeWay; ● Can compare a nullable type to null It's an error to read Value when == null. That includes casting to base type.

Nullable types add null ● An unset value that you can test inline. Don't have to declare special flag value in each enum. To test float point NAN, have to call double.IsNaN(). ● Reference types can already be null Can't have string? or any other nullable reference type ● C# hoists operators so they work with null Only calls operators with non-null values ● Boxing behavior

That's It For Generics Any Quick Questions?

Iterators IEnumerable and IEnumerator Tiny little nested objects Easy to enumerate linear list Nested structures take state machines That is, complicated and fragile Iterators compile yield return code to a state machine. Even recursive code!

Iterator example public IEnumerator GetEnumerator() { foreach (FileSystemInfo Info in Unsorted(Root)) yield return Info; } private IEnumerable Unsorted(DirectoryInfo Path) { foreach (FileSystemInfo Info in Path.GetFileSystemInfos()) { yield return Info; DirectoryInfo Directory = Info as DirectoryInfo; if (Directory != null) foreach (FileSystemInfo Child in Unsorted(Directory)) yield return Child; }

Simple delegate enhancements ● Speed Interface was 250% faster than delegate in 1.x Delegates are ca 5% faster than interfaces in 2.x ● New method group syntax DelegateType DelegateInstance = Instance.Method; Don't have to say new DelegateType() Just like Delphi... Instance.Method specifies an overload method group Valid delegate if one and only one overload in group

Advanced delegates ● Anonymous Methods ● Covariance and Contravariance ● Call delegates asynchronously Think of them as asynch primitives

What's Wrong With Named Methods? ● In C# 1.0, delegates always refer to normal, named methods ● Three problems: ● Clutter and bloat. ● No tie between callback and caller. ● Boilerplate - copying local variables to tiny state objects to support callbacks &c.

Anonymous Methods ● That is – Defining a method just so that you can create a delegate to it makes your code harder to write and harder to read. ● So – C# 2.0 supports anonymous methods, which let you create a delegate to a special statement block, within a method.

Delegate expressions ● delegate (optional parameters) {} ● Valid in delegate expressions – In assignment DelegateType DelegateInstance = delegate(int N) {}; // note the ; after the } – As a parameter to a method Fn(delegate {}) – Event list editing SomeEvent += delegate(object sender, EventArgs E) {};

Capture ● Anonymous methods can capture parameters and/or local variables ● Captured variables are implemented as fields in a singleton instance of a Compiler Generated Class. Captured parameters are copied in, by method prolog, then only referred to as CGC fields. ● Captured variables last as long as the delegate lasts. ● Anonymous methods are named methods of the CGC.

Covariance class Base { public static Derived BaseFn(Base B) { return new Derived(); } } class Derived : Base {} delegate Base BaseFunction(Base B); ● In 1.x, can’t say BaseFunction F = new BaseFunction(Base.BaseFn) A BaseFunction returns a Base instance Base.BaseFn returns a Derived instance. ● Can, in 2.x Every Derived instance is also a Base instance

Contravariance class Base { public static void BaseProc(Base B) { } } class Derived : Base { public static void DerivedProc(Derived D) { } } delegate void BaseMethod(Base B); delegate void DerivedMethod(Derived D); ● A method that takes a base type is compatible with a delegate that takes a derived type: DerivedMethod BaseD = new DerivedMethod(Base.BaseProc);

Complicated Names ● Practical effect is that matching is looser. ● You'll probably only notice covariance and contravariance when 2.0 code won't compile under 1.x, “even though it's not using generics” ● Don't put effort into telling them apart, or even remembering details of how matching is looser

Asynchronous Calls ● Available in 1.0 ● Call any delegate via.BeginInvoke() Runs in ThreadPool thread. ● Collect results with.EndInvoke() Do something while waiting for disk IO. Get ready for the multicore future. Less overhead than creating new Thread. Less os work, and less user code

Asynchronous Example public class ThreadEach { public delegate void Processor(T Datum); public static void Process(Processor P, IEnumerable Data) { //foreach (T Datum in Data) // P(Datum); // Process each Datum in the current thread List AsyncResults = new List (); // Process each Datum in its own thread foreach (T Datum in Data) AsyncResults.Add(P.BeginInvoke(Datum, null, null)); // Wait for all threads to finish foreach (IAsyncResult Async in AsyncResults) P.EndInvoke(Async); }

Partial Types partial class Fred { protected int This; } partial class Fred{ protected int That; } – Only one definition needs to have an access modifier like public or internal ● Multiple access modifiers, must all agree. ● Can’t have public partial class Partial {} and internal partial class Partial {}! – Similarly, only needs one base class ● Multiple base classes, all must agree.

Thank you Any Questions?

Midnight Beach Contracting Consulting Training

Jon Shemitz Talks fast. Codes fast, too.