Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual C# 2005: IDE Enhancements Dan Fernandez C# Product Manager

Similar presentations


Presentation on theme: "Visual C# 2005: IDE Enhancements Dan Fernandez C# Product Manager"— Presentation transcript:

1 Visual C# 2005: IDE Enhancements Dan Fernandez C# Product Manager danielfe@microsoft.com http://blogs.msdn.com/danielfe/

2 2 Agenda Generics Anonymous methods Nullable types Iterators Partial types and many more… 100% backwards compatible

3 3 Generics What are they? –Code that allows you to pass the data type as a parameter. –Rather then explicitly declaring the data type (int, string) when writing code, you use a generic data type instead Benefits –Code reusability –Type checking, no boxing, no downcasts –Reduced code bloat (typed collections)

4 4 Generic Basics T can be used for any numerical type public struct Point { public T X; public T X; public T Y; public T Y;} Point point; point.X = 10; point.Y = 20; Point point; point.X = 1.2f; point.Y = 3.4f; public struct Point { public int X; public int X; public int Y; public int Y;} public struct Point { public float X; public float X; public float Y; public float Y;} public struct Point { public long X; public long X; public long Y; public long Y;}

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

6 6 Generics 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 through reflection –JIT compiler replaces generic IL with object references –Specific to App Domain Value types –Compiler will create one version for each value type (one for int, one for long, etc) –Reused for same value type Reference types –Compiler will create one version for all reference types Ex: Customer class, DataSet, Orders class –Reused in all further encounters of all other reference types

7 7 Generics 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 numberSpellings;

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

9 9 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() 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) { … }}

10 10 Generic Constraints Zero or one primary constraint –Actual class, class, or struct Zero or more secondary constraints –Interface or type parameter Zero or one constructor constraint –new() public struct Point : struct { public T X; public T X; public T Y; public T Y;} Point point; point.X = 1.2f; point.Y = 3.4f;

11 11 Generics 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}

12 12 Generics in the.NET Framework Collection classes Collection interfaces Collection base classes Utility classes Reflection LinkedList List LinkedList List 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> Native support in IL and CLR

13 Generics Performance

14 14 What’s wrong with this code? SqlCommand cmd = new SqlCommand(); using (SqlDataReader rs = cmd.ExecuteReader()) using (SqlDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) while (rs.Read()) { int Age; int Age; Age = (int)rs["Age"]; Age = (int)rs["Age"]; Console.WriteLine(Age); Console.WriteLine(Age); } } Age---------3050null21

15 15 Nullable Types System.Nullable –Provides nullability for any value type –Struct that combines a T and a bool public struct Nullable where T: struct { public Nullable(T value) {...} public Nullable(T value) {...} public T Value { get {...} } public T Value { get {...} } public bool HasValue { get {...} } public bool HasValue { get {...} }......} Nullable x = new Nullable (123);... if (x.HasValue) { Console.WriteLine(x.Value); Console.WriteLine(x.Value);}

16 16 Nullable Types T? same as System.Nullable null literal conversions Nullable conversions int? x = 123; double? y = 1.25; int? x = null; double? y = null; int i = 123; int? x = i;// int --> int? double? y = x;// int? --> double?

17 17 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); }; }; }}

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

19 19 Generic Delegates in the.NET Framework Action - Performs an action on the specified object Predicate - Defines a set of criteria data must meet Converter - Converts from one type to another type Comparison - Compares two objects of the same type public sealed delegate void Action ( T obj ); public sealed delegate bool Predicate ( T obj ); public sealed delegate U Converter ( T from ); public sealed delegate int Comparison ( T x, T y );

20 20 List Methods that use Generic Delegates ForEach - Performs specified action on each element Find/FindIndex/FindAll/FindLast – Filters data based on condition ConvertAll - Converts all to another type TrueForAll - Determines whether every element meets criteria in predicate public List FindAll( Predicate match ); public void ForEach( Action action ); public List ConvertAll ( Converter converter ); public bool TrueForAll( Predicate match );

21 21 Using Anonymous Methods List numbers = new List (); numbers.Add(1);numbers.Add(1); numbers.Add(6); numbers.Add(2); int sum = 0; numbers.ForEach(delegate(int i) { sum += i; }); { sum += i; }); Console.WriteLine(sum); //Print 10 int match = numbers.FindIndex(delegate(int i) { return i == 6; }); { return i == 6; }); Console.WriteLine(match); //Print 2 bool check = numbers.TrueForAll(delegate(int i) { return i > 0; }); { return i > 0; }); Console.WriteLine(check); //Print True ForEach FindIndex TrueForAll Generic List

22 Anonymous Methods

23 23 Iterators 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);}

24 24 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]; } }}

25 25 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 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; } }}

26 26 public class List public class List { public IEnumerator GetEnumerator() { public IEnumerator GetEnumerator() { for (int i = 0; i < count; 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--) 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)) {…}

27 Iterators

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

29 29 Partial Types Break source code into multiple source files –IDE generated vs custom code IL emitted as if it is one file No messy linking –csc customer1.cs customer2.cs Can provide overloads in different classes –Signature must be different Customer.Sell() Customer.Sell(currency ) Both Web and Windows Forms use partial classes for Designer Generated code

30 30 Static Classes Only static members Cannot be used as type of variable, parameter, field, property, … Examples include System.Console, System.Environment 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) {...}......}

31 31 Property Accessors Property accessor accessibility –Allows one accessor to be restricted further –Typically set {…} more restricted than get {…} public class Customer { private string _CustomerID; private string _CustomerID; public string CustomerID { public string CustomerID { get { return id; } get { return id; } internal set { id = value; } internal set { id = value; } }}

32 32 External Aliases Enables use of identically named types in different assemblies namespace Stuff { public class Utils public class Utils { public static void F() {...} public static void F() {...} }} namespace Stuff { public class Utils public class Utils { public static void F() {...} public static void F() {...} }} foo.dll bar.dll extern alias Foo; extern alias Bar; class Program { static void Main() { static void Main() { Foo.Stuff.Utils.F(); Foo.Stuff.Utils.F(); Bar.Stuff.Utils.F(); Bar.Stuff.Utils.F(); }} C:\>csc /r:Foo=foo.dll /r:Bar=bar.dll test.cs

33 33 Inline Warning Control #pragma warning 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 }}

34 34 Fixed Size Buffers C style 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];}

35 35 Resources Visual C# Developer Center –http://msdn.microsoft.com/vcsharp/http://msdn.microsoft.com/vcsharp/ MSDN Forums –http://forums.msdn.comhttp://forums.msdn.com Email –danielfe@microsoft.comdanielfe@microsoft.com

36 36 © 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.


Download ppt "Visual C# 2005: IDE Enhancements Dan Fernandez C# Product Manager"

Similar presentations


Ads by Google