1 Visual C# "Whidbey": Language Enhancements Anders Hejlsberg Distinguished Engineer Microsoft Corporation Anders Hejlsberg Distinguished.

Slides:



Advertisements
Similar presentations
The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
Advertisements

CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Introduction to Web Application
Basic Java Constructs and Data Types – Nuts and Bolts
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Program Verification Using the Spec# Programming System ETAPS Tutorial K. Rustan M. Leino, Microsoft Research, Redmond Rosemary Monahan, NUIM Maynooth.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Structure and Union Types Problem Solving & Program Design.
12 Copyright © 2005, Oracle. All rights reserved. Structuring Code Using Abstract Classes and Interfaces.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
Semantic Analysis and Symbol Tables
Dictionaries, Hash Tables, Collisions Resolution, Sets Svetlin Nakov Telerik Corporation
Microsoft Access.
1 / / / /. 2 (Object) (Object) –, 10 (Class) (Class) –, –, – (Variables) [ Data member Field Attribute](, ) – (Function) [ Member function Method Operation.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 12 – Security Panel Application Introducing.
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
VOORBLAD.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
1 of 31 Images from Africa. 2 of 31 My little Haitian friend Antoine (1985)
1 of 32 Images from Africa. 2 of 32 My little Haitian friend Antoine (1985)
 Anders Hejlsberg Technical Fellow Microsoft Corporation TL16.
Macromedia Dreamweaver MX 2004 – Design Professional Dreamweaver GETTING STARTED WITH.
25 seconds left…...
Januar MDMDFSSMDMDFSSS
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
PSSA Preparation.
Process Trees + Properties Dennis Schunselaar. Process Trees 2 Visualiser 1: Visualiser 2:
Computer Programming and Basic Software Engineering 9 Building Graphical User Interface Developing a Simple Graphical User Interface (GUI)
Data Structures Using C++ 2E
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
 2007 Dr. Natheer Khasawneh. Chapter 13. Graphical User Interface Concepts: Part 1.
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
DEV340 Microsoft Visual C# Under the Covers: An In-Depth Look at C# 2.0 Anders Hejlsberg Distinguished Engineer Microsoft Corporation.
Overview of Visual C# 2005 Henrik Westergaard Hansen
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++
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
Visual C# 2005: IDE Enhancements Dan Fernandez C# Product Manager
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
C Sharp Web & Internet Programming Group Diana, Aren, Jeff, & Adam, Farrin 5/5/20081CS 311.
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.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
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.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Visual C# "Whidbey": Language Enhancements
Visual C# 2005: Language Enhancements
DEV321 Visual C# 2005: Language Enhancements
Getting Ready for Visual Studio 2005
How to organize and document your classes
Visual C# 2005: Language Enhancements
Presentation transcript:

1 Visual C# "Whidbey": Language Enhancements Anders Hejlsberg Distinguished Engineer Microsoft Corporation Anders Hejlsberg Distinguished Engineer Microsoft Corporation Session Code: TLS320

2 C# Language Enhancements Generics Anonymous methods Iterators Partial types Other enhancements Generics Anonymous methods Iterators Partial types Other enhancements

3 public class List { private object[] elements; private object[] elements; private int count; private int count; public void Add(object element) { public void Add(object element) { if (count == elements.Length) Resize(count * 2); if (count == elements.Length) Resize(count * 2); elements[count++] = element; elements[count++] = element; } public object this[int index] { public object this[int index] { get { return elements[index]; } get { return elements[index]; } set { elements[index] = value; } set { elements[index] = value; } } public int Count { public int Count { get { return count; } get { return count; } }} Generics public class List public class List { private T[] elements; private T[] elements; private int count; private int count; public void Add(T element) { public void Add(T element) { if (count == elements.Length) Resize(count * 2); if (count == elements.Length) Resize(count * 2); elements[count++] = element; elements[count++] = element; } public T this[int index] { public T this[int index] { get { return elements[index]; } get { return elements[index]; } set { elements[index] = value; } set { elements[index] = value; } } public int Count { public int Count { get { return count; } get { return count; } }} List intList = new List(); intList.Add(1);intList.Add(2);intList.Add("Three"); int i = (int)intList[0]; List intList = new List(); intList.Add(1);// Argument is boxed intList.Add(2);// Argument is boxed intList.Add("Three");// Should be an error int i = (int)intList[0];// Cast required List intList = new List (); intList.Add(1);// No boxing intList.Add(2);// No boxing intList.Add("Three");// Compile-time error int i = intList[0];// No cast required

4 Generics Why generics? Type checking, no boxing, no downcasts Reduced code bloat (typed collections) How are C# generics implemented? Instantiated at run-time, not compile-time Checked at declaration, not instantiation Work for both reference and value types Complete run-time type information Why generics? Type checking, no boxing, no downcasts Reduced code bloat (typed collections) How are C# generics implemented? Instantiated at run-time, not compile-time Checked at declaration, not instantiation Work for both reference and value types Complete run-time type information

5 Generics Type parameters can be applied to Class, struct, interface, and delegate types Type parameters can be applied to Class, struct, interface, and delegate types class Dictionary {…} struct HashBucket {…} interface IComparer {…} delegate R Function (A arg); Dictionary customerLookupTable; Dictionary > orderLookupTable; Dictionary wordCount;

6 Generics Type parameters can be applied to Class, struct, interface, and delegate types Methods Type parameters can be applied to Class, struct, interface, and delegate types Methods class Utils { public static T[] CreateArray (int size) { public static T[] CreateArray (int size) { return new T[size]; return new T[size]; } public static void SortArray (T[] array) { public static void SortArray (T[] array) { … }} string[] names = Utils.CreateArray (3); names[0] = "Jones"; names[1] = "Anderson"; names[2] = "Williams"; Utils.SortArray(names);

7 Generics Type parameters can be applied to Class, struct, interface, and delegate types Methods Type parameters can have constraints One base class, multiple interfaces, new() Type parameters can be applied to Class, struct, interface, and delegate types Methods Type parameters can have constraints One base class, multiple interfaces, new() class Dictionary class Dictionary { public void Add(K key, V value) { public void Add(K key, V value) { … if (((IComparable)key).CompareTo(x) == 0) {…} if (((IComparable)key).CompareTo(x) == 0) {…} … }} class Dictionary where K: IComparable { public void Add(K key, V value) { public void Add(K key, V value) { … if (key.CompareTo(x) == 0) {…} if (key.CompareTo(x) == 0) {…} … }} class Dictionary : IDictionary class Dictionary : IDictionary where K: IComparable where K: IComparable where V: IKeyProvider, IPersistable, new() where V: IKeyProvider, IPersistable, new() { public void Add(K key, V value) { … }}

8 public class List public class List { public void Add(T item) {…} public void Add(T item) {…} public T this[int index] {…} public T this[int index] {…} …} public class List : IList { public void Add(T item) {…} public void Add(T item) {…} public T this[int index] {…} public T this[int index] {…} …} public interface IList { public void Add(object item); public void Add(object item); public object this[int index] {…} public object this[int index] {…} …} Generics Generics are invariant Interfaces can be used for type neutrality Generics are invariant Interfaces can be used for type neutrality List<object>List<int>List<string> object

9 Generics T.default Null checks Type casts T.default Null checks Type casts void Foo () { T x = null;// Error T x = null;// Error T y = T.default;// Ok T y = T.default;// Ok} void Foo (T x) { if (x == null) { if (x == null) { throw new FooException(); throw new FooException(); } …} void Foo (T x) { int i = (int)x;// Error int i = (int)x;// Error int j = (int)(object)x;// Ok int j = (int)(object)x;// Ok}

10 Generics Collection classes Collection interfaces Collection base classes Utility classes Reflection Collection classes Collection interfaces Collection base classes Utility classes Reflection List<T>Dictionary<K,V>SortedDictionary<K,V>Stack<T>Queue<T> IList<T>IDictionary<K,V>ICollection<T>IEnumerable<T>IEnumerator<T>IComparable<T>IComparer<T> Collection<T>KeyedCollection<T>ReadOnlyCollection<T> Nullable<T>EventHandler<T>Comparer<T>

11 Generics System.Nullable Provides nullability for any type Struct that combines a T and a bool Conversions between T and Nullable Conversion from null literal to Nullable System.Nullable Provides nullability for any type Struct that combines a T and a bool Conversions between T and Nullable Conversion from null literal to Nullable Nullable x = 123; Nullable y = null; int i = (int)x; int j = x.Value; if (x.HasValue) Console.WriteLine(x.Value);

12 Anonymous Methods class MyForm : Form { ListBox listBox; ListBox listBox; TextBox textBox; TextBox textBox; Button addButton; Button addButton; public MyForm() { public MyForm() { listBox = new ListBox(...); listBox = new ListBox(...); textBox = new TextBox(...); textBox = new TextBox(...); addButton = new Button(...); addButton = new Button(...); addButton.Click += new EventHandler(AddClick); addButton.Click += new EventHandler(AddClick); } void AddClick(object sender, EventArgs e) { void AddClick(object sender, EventArgs e) { listBox.Items.Add(textBox.Text); listBox.Items.Add(textBox.Text); }} class MyForm : Form { ListBox listBox; ListBox listBox; TextBox textBox; TextBox textBox; Button addButton; Button addButton; public MyForm() { public MyForm() { listBox = new ListBox(...); listBox = new ListBox(...); textBox = new TextBox(...); textBox = new TextBox(...); addButton = new Button(...); addButton = new Button(...); addButton.Click += delegate { addButton.Click += delegate { listBox.Items.Add(textBox.Text); listBox.Items.Add(textBox.Text); }; }; }}

13 Anonymous Methods Allows code block in place of delegate Delegate type automatically inferred Code block can be parameterless Or code block can have parameters In either case, return types must match Allows code block in place of delegate Delegate type automatically inferred Code block can be parameterless Or code block can have parameters In either case, return types must match button.Click += delegate { MessageBox.Show("Hello"); }; button.Click += delegate(object sender, EventArgs e) { MessageBox.Show(((Button)sender).Text); };

14 Anonymous Methods Code block can access local variables delegate bool Predicate (T item); public class List public class List { public List FindAll(Predicate filter) { public List FindAll(Predicate filter) { List result = new List (); List result = new List (); foreach (T item in this) { foreach (T item in this) { if (filter(item)) result.Add(item); if (filter(item)) result.Add(item); } return result; return result; }} public class Bank { List accounts; List accounts; List GetOverdrawnAccounts() { List GetOverdrawnAccounts() { return accounts.FindAll(delegate(Account a) { return accounts.FindAll(delegate(Account a) { return a.Balance < 0; return a.Balance < 0; }); }); } List GetLargeAccounts(double minBalance) { List GetLargeAccounts(double minBalance) { return accounts.FindAll(delegate(Account a) { return accounts.FindAll(delegate(Account a) { return a.Balance >= minBalance; return a.Balance >= minBalance; }); }); }} public class Bank { List GetLargeAccounts(double minBalance) { List GetLargeAccounts(double minBalance) { Helper helper = new Helper(); Helper helper = new Helper(); helper.minBalance = minBalance; helper.minBalance = minBalance; return accounts.FindAll(helper.Matches); return accounts.FindAll(helper.Matches); } internal class Helper internal class Helper { internal double minBalance; internal double minBalance; internal bool Matches(Account a) { internal bool Matches(Account a) { return a.Balance >= minBalance; return a.Balance >= minBalance; } } } } }

15 Anonymous Methods Method group conversions Delegate type inferred when possible Method group conversions Delegate type inferred when possible using System; using System.Threading; class Program { static void Work() {…} static void Work() {…} static void Main() { static void Main() { Thread t = new Thread(new ThreadStart(Work)); Thread t = new Thread(new ThreadStart(Work)); t.Start(); t.Start(); }} using System; using System.Threading; class Program { static void Work() {…} static void Work() {…} static void Main() { static void Main() { Thread t = new Thread(Work); Thread t = new Thread(Work); t.Start(); t.Start(); }}

16 Generics Performance

17 Iterators foreach relies on enumerator pattern GetEnumerator() method foreach makes enumerating easy But enumerators are hard to write! foreach relies on enumerator pattern GetEnumerator() method foreach makes enumerating easy But enumerators are hard to write! foreach (object obj in list) { DoSomething(obj); DoSomething(obj);} Enumerator e = list.GetEnumerator(); while (e.MoveNext()) { object obj = e.Current; object obj = e.Current; DoSomething(obj); DoSomething(obj);}

18 Iterators public class List { internal object[] elements; internal object[] elements; internal int count; internal int count; public ListEnumerator GetEnumerator() { return new ListEnumerator(this); public ListEnumerator GetEnumerator() { return new ListEnumerator(this); }} public class ListEnumerator : IEnumerator { List list; List list; int index; int index; internal ListEnumerator(List list) { internal ListEnumerator(List list) { this.list = list; this.list = list; index = -1; index = -1; } public bool MoveNext() { public bool MoveNext() { int i = index + 1; int i = index + 1; if (i >= list.count) return false; if (i >= list.count) return false; index = i; index = i; return true; return true; } public object Current { public object Current { get { return list.elements[index]; } get { return list.elements[index]; } }}

19 public class List { public IEnumerator GetEnumerator() { public IEnumerator GetEnumerator() { for (int i = 0; i < count; i++) { yield return elements[i]; for (int i = 0; i < count; i++) { yield return elements[i]; } }} Iterators Method that incrementally computes and returns a sequence of values yield return and yield break Must return IEnumerator or IEnumerable Method that incrementally computes and returns a sequence of values yield return and yield break Must return IEnumerator or IEnumerable public IEnumerator GetEnumerator() { return new __Enumerator(this); return new __Enumerator(this);} private class __Enumerator: IEnumerator { object current; object current; int state; int state; public bool MoveNext() { public bool MoveNext() { switch (state) { switch (state) { case 0: … case 0: … case 1: … case 1: … case 2: … case 2: … … } } public object Current { public object Current { get { return current; } get { return current; } }}

20 public class List public class List { public IEnumerator GetEnumerator() { public IEnumerator GetEnumerator() { for (int i = 0; i < count; i++) yield return elements[i]; for (int i = 0; i < count; i++) yield return elements[i]; } public IEnumerable Descending() { public IEnumerable Descending() { for (int i = count - 1; i >= 0; i--) yield return elements[i]; for (int i = count - 1; i >= 0; i--) yield return elements[i]; } public IEnumerable Subrange(int index, int n) { public IEnumerable Subrange(int index, int n) { for (int i = 0; i < n; i++) yield return elements[index + i]; for (int i = 0; i < n; i++) yield return elements[index + i]; }} Iterators List items = GetItemList(); foreach (Item x in items) {…} foreach (Item x in items.Descending()) {…} foreach (Item x in Items.Subrange(10, 20)) {…}

21 Partial Types public partial class Customer { private int id; private int id; private string name; private string name; private string address; private string address; private List orders; private List orders;} public partial class Customer { public void SubmitOrder(Order order) { public void SubmitOrder(Order order) { orders.Add(order); orders.Add(order); } public bool HasOutstandingOrders() { public bool HasOutstandingOrders() { return orders.Count > 0; return orders.Count > 0; }} public class Customer { private int id; private int id; private string name; private string name; private string address; private string address; private List orders; private List orders; public void SubmitOrder(Order order) { public void SubmitOrder(Order order) { orders.Add(order); orders.Add(order); } public bool HasOutstandingOrders() { public bool HasOutstandingOrders() { return orders.Count > 0; return orders.Count > 0; }}

22 Partial Types

23 Other Enhancements Static classes Can contain only static members Cannot be type of variable, parameter, etc. System.Console, System.Environment, etc. Static classes Can contain only static members Cannot be type of variable, parameter, etc. System.Console, System.Environment, etc. public static class Math { public static double Sin(double x) {…} public static double Sin(double x) {…} public static double Cos(double x) {…} public static double Cos(double x) {…} …}

24 Other Enhancements Property accessor accessibility Allows one accessor to be restricted further Typically set {…} more restricted than get {…} Property accessor accessibility Allows one accessor to be restricted further Typically set {…} more restricted than get {…} public class Customer { private string id; private string id; public string CustomerId { public string CustomerId { get { return id; } get { return id; } internal set { id = value; } internal set { id = value; } }}

25 Other Enhancements Namespace alias qualifier A::B looks up A only as namespace alias global::X starts lookup in global namespace Namespace alias qualifier A::B looks up A only as namespace alias global::X starts lookup in global namespace using IO = System.IO; class Program { static void Main() { static void Main() { IO::Stream s = new IO::File.OpenRead("foo.txt"); IO::Stream s = new IO::File.OpenRead("foo.txt"); global::System.Console.WriteLine("Hello"); global::System.Console.WriteLine("Hello"); }}

26 Other Enhancements Fixed size buffers C style embedded arrays in unsafe code Fixed size buffers C style embedded arrays in unsafe code public struct OFSTRUCT { public byte cBytes; public byte cBytes; public byte fFixedDisk; public byte fFixedDisk; public short nErrCode; public short nErrCode; private int Reserved; private int Reserved; public fixed char szPathName[128]; public fixed char szPathName[128];}

27 Other Enhancements #pragma warning Control individual warnings in blocks of code #pragma warning Control individual warnings in blocks of code using System; class Program { [Obsolete] [Obsolete] static void Foo() {} static void Foo() {} static void Main() { static void Main() { #pragma warning disable 612 Foo(); Foo(); #pragma warning restore 612 }}

28 C# and CLI Standardization Work begun in September 2000 Intel, HP, IBM, Fujitsu, Plum Hall, and others ECMA standards ratified December 2001 ISO standards published April 2003 Several CLI and C# implementations.NET Framework and Visual Studio.NET SSCLI – Shared source on XP, FreeBSD, OS X Mono – Open source on Linux Standardization of new features ongoing Work begun in September 2000 Intel, HP, IBM, Fujitsu, Plum Hall, and others ECMA standards ratified December 2001 ISO standards published April 2003 Several CLI and C# implementations.NET Framework and Visual Studio.NET SSCLI – Shared source on XP, FreeBSD, OS X Mono – Open source on Linux Standardization of new features ongoing

29 Book signing, Exhibition Hall Book Store, Wednesday, 1-2pm

30 Q & A C# Language home page ECMA C# Standard publications/standards/ecma-334.htm Panel: The Future of.NET Languages PNL10, Thursday, 1:45pm – 3:15pm Tools Lounge (near Hall A) Tuesday, 5:15pm – 6:30pm Wednesday, 3:00pm – 5:00pm C# Language home page ECMA C# Standard publications/standards/ecma-334.htm Panel: The Future of.NET Languages PNL10, Thursday, 1:45pm – 3:15pm Tools Lounge (near Hall A) Tuesday, 5:15pm – 6:30pm Wednesday, 3:00pm – 5:00pm

31 © Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.