Presentation is loading. Please wait.

Presentation is loading. Please wait.

C#C# C#C# Kit Colbert Student Consultant representing Microsoft

Similar presentations


Presentation on theme: "C#C# C#C# Kit Colbert Student Consultant representing Microsoft"— Presentation transcript:

1 C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

2 C# Design goals Design goals Unified type system Unified type system Component-oriented features Component-oriented features Productivity features Productivity features C# futures C# futures Standardization Standardization

3 C# design goals Dramatically increase productivity Dramatically increase productivity Provide unified and extensible type system Provide unified and extensible type system Support component-oriented programming Support component-oriented programming Enable robust and durable applications Enable robust and durable applications Build foundation for future innovation Build foundation for future innovation

4 Unified type system Traditional views of primitive types Traditional views of primitive types  C++, Java: They’re “special”  Smalltalk, Lisp: They’re full-blown objects C# unifies with no performance cost C# unifies with no performance cost  Value types, boxing and unboxing  Deep simplicity throughout system Improved extensibility and reusability Improved extensibility and reusability  New primitive types: Decimal, SQL…  Collections, etc., work for all types

5 Value and reference types Value types Value types  Variables directly contain data  Cannot be null Reference types Reference types  Variables contain references to objects  May be null int i = 123; string s = "Hello world"; 123 i s "Hello world"

6 Value and reference types Value types Value types  Primitives int i; double x;  Enums enum State { Off, On }  Structs struct Point { int x, y; } Reference types Reference types  Classes class Foo: Bar, IFoo {...}  Interfaces interface IFoo: IBar {...}  Arrays Foo[] a = new Foo[10];  Delegates delegate void Empty();

7 Classes Inheritance Inheritance  Single base class (System.Object)  Multiple interface implementations Class members Class members  Static and instance members  Nested types Member access Member access  Public, protected, internal, private

8 Structs Like classes, except Like classes, except  Stored in-line, not heap allocated  Assignment copies data, not reference  Always inherit directly from System.Object Ideal for light weight objects Ideal for light weight objects  Complex, Point, Rectangle, Color  int, float, double, etc., are all structs No heap allocation, less GC pressure No heap allocation, less GC pressure More efficient use of memory More efficient use of memory

9 Classes and structs class CPoint { int x, y;... } class CPoint { int x, y;... } struct SPoint { int x, y;... } CPoint cp = new CPoint(10, 20); SPoint sp = new SPoint(10, 20); 10 20 sp cp 10 20 CPoint

10 Unified type system Boxing Boxing  Allocates box, copies value into it Unboxing Unboxing  Checks type of box, copies value out int i = 123; object o = i; int j = (int)o; 123 i o 123 System.Int32 123 j

11 Unified type system Several benefits Several benefits  Eliminates “wrapper classes”  Collection classes work with all types Lots of examples in.NET Framework Lots of examples in.NET Framework string s = string.Format( "On {0} your balance was {1}", date, balance); "On {0} your balance was {1}", date, balance); Hashtable t = new Hashtable(); t.Add(0, "zero"); t.Add(1, "one"); t.Add(2, "two");

12 Component-oriented features What defines a component? What defines a component?  Properties, methods, events, attributes C# has first class support C# has first class support  Not naming patterns, adapters, etc.  Not external files Components are easy to build and consume Components are easy to build and consume

13 Properties First class language construct First class language construct public class Button: Control { private string text; private string text; public string Text { public string Text { get { get { return text; return text; } set { set { text = value; text = value; Repaint(); Repaint(); } }} Button b = new Button(); b.Text = "OK"; string s = b.Text;

14 Events First class language construct First class language construct public delegate void EventHandler( object sender, EventArgs e); object sender, EventArgs e); public class Button: Control { public event EventHandler Click; protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); } protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); }} void Initialize() { Button b = new Button(...); Button b = new Button(...); b.Click += new EventHandler(ButtonClick); b.Click += new EventHandler(ButtonClick);} void ButtonClick(object sender, EventArgs e) { MessageBox.Show("You pressed the button"); MessageBox.Show("You pressed the button");}

15 Attributes How do you associate information with types and members? How do you associate information with types and members?  Category of a property  Transaction context for a method  XML persistence mapping Traditional solutions Traditional solutions  Add keywords or pragmas to language  Use external files (e.g.,.IDL,.DEF) C# solution: Attributes C# solution: Attributes

16 Attributes public class Button: Control { [Category("Appearance")] [Category("Appearance")] [Description("Color of text in button")] [Description("Color of text in button")] [Browsable(true)] [Browsable(true)] public Color TextColor {...} public Color TextColor {...} protected override void Paint(Graphics g) { protected override void Paint(Graphics g) { TextOut(g.GetHdc(), 10, 10, "Hello"); TextOut(g.GetHdc(), 10, 10, "Hello"); } [DllImport("gdi32", CharSet = CharSet.Auto)] [DllImport("gdi32", CharSet = CharSet.Auto)] static extern bool TextOut(int hDC, static extern bool TextOut(int hDC, int x, int y, string text); int x, int y, string text);} public class CategoryAttribute: System.Attribute { public readonly string Value; public readonly string Value; public CategoryAttribute(string s) { public CategoryAttribute(string s) { Value = s; Value = s; }} Type type = typeof(Button); foreach (Attribute a in type.GetCustomAttributes()) { CategoryAttribute ca = a as CategoryAttribute; CategoryAttribute ca = a as CategoryAttribute; if (ca != null) { if (ca != null) { Console.WriteLine(ca.Value); Console.WriteLine(ca.Value); }}

17 Attributes Completely extensible Completely extensible  New attributes are created by inheriting from System.Attribute Type-safe Type-safe  Arguments checked at compile-time  Examined using reflection at run-time Extensive use in.NET frameworks Extensive use in.NET frameworks  XML, Web Services, security, serialization, component model, COM and P/Invoke interop, code configuration…

18 Productivity features parameter arrays parameter arrays ref and out parameters ref and out parameters overflow checking overflow checking foreach statement foreach statement using statement using statement switch on string switch on string

19 Parameter arrays Can write “printf” style methods Can write “printf” style methods Type-safe, unlike C++ Type-safe, unlike C++ static void printf(string fmt, params object[] args) { foreach (object x in args) { foreach (object x in args) {...... }} printf("%s %i", s, i); object[] args = new object[2]; args[0] = s; args[1] = i; printf("%s %i", args);

20 ref and out parameters Use “ref” for in/out parameter passing Use “ref” for in/out parameter passing Use “out” to return multiple values Use “out” to return multiple values Must repeat ref/out at call site Must repeat ref/out at call site static void Swap(ref int a, ref int b) {...} static void Divide(int dividend, int divisor, out int result, out int remainder) {...} out int result, out int remainder) {...} static void Main() { int x = 1, y = 2; int x = 1, y = 2; Swap(ref x, ref y); Swap(ref x, ref y);}

21 Overflow checking Integer arithmetic operations Integer arithmetic operations  C, C++, Java silently overflow checked vs. unchecked contexts checked vs. unchecked contexts  Default is unchecked, except for constants  Change with “/checked” compiler switch int i = checked(x * y); checked { int i = x * y; int i = x * y;}

22 foreach statement Iteration of arrays Iteration of arrays Iteration of IEnumerable collections Iteration of IEnumerable collections ArrayList accounts = Bank.GetAccounts(...); foreach (Account a in accounts) { if (a.Balance < 0) Console.WriteLine(a.CustName); if (a.Balance < 0) Console.WriteLine(a.CustName);} public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); foreach (string s in args) Console.WriteLine(s);}

23 using statement static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); Stream output = File.Create(destName); byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } output.Close(); output.Close(); input.Close(); input.Close();} static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); try { try { Stream output = File.Create(destName); Stream output = File.Create(destName); try { try { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } } finally { finally { output.Close(); output.Close(); } } finally { finally { input.Close(); input.Close(); }} static void Copy(string sourceName, string destName) { using (Stream input = File.OpenRead(sourceName)) using (Stream input = File.OpenRead(sourceName)) using (Stream output = File.Create(destName)) { using (Stream output = File.Create(destName)) { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } }}

24 using statement Acquire, Execute, Release pattern Acquire, Execute, Release pattern Works with any IDisposable object Works with any IDisposable object  Data access classes, streams, text readers and writers, network classes, etc. using (Resource res = new Resource()) { res.DoWork(); res.DoWork();} Resource res = new Resource(...); try { res.DoWork(); res.DoWork();} finally { if (res != null) ((IDisposable)res).Dispose(); if (res != null) ((IDisposable)res).Dispose();}

25 Switch on string Color ColorFromFruit(string s) { switch(s.ToLower()) { switch(s.ToLower()) { case "apple": case "apple": return Color.Red; return Color.Red; case "banana": case "banana": return Color.Yellow; return Color.Yellow; case "carrot": case "carrot": return Color.Orange; return Color.Orange; default: default: throw new InvalidArgumentException(); throw new InvalidArgumentException(); }}

26 C# futures Generics Generics Iterators Iterators Anonymous methods Anonymous methods Partial types Partial types

27 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 ItemType[] elements; private ItemType[] elements; private int count; private int count; public void Add(ItemType element) { public void Add(ItemType element) { if (count == elements.Length) Resize(count * 2); if (count == elements.Length) Resize(count * 2); elements[count++] = element; elements[count++] = element; } public ItemType this[int index] { public ItemType 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

28 Generics Why generics? Why generics?  Compile-time type checking  Performance (no boxing, no downcasts)  Reduced code bloat (typed collections) C# generics vs. C++ templates C# generics vs. C++ templates  C# generics are checked at declaration  C# generics are instantiated at run-time C# generics vs. proposed Java generics C# generics vs. proposed Java generics  C# generics work over entire type system  C# generics preserve types at run-time

29 Generics Type parameters can be applied to Type parameters can be applied to  Class, struct, interface, and delegate types class Dictionary {...} struct Pair {...} interface IComparer {...} delegate ResType Func (ArgType arg); Dictionary customerLookupTable; Dictionary > orderLookupTable; Dictionary numberSpellings;

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

31 Generics Constraints Constraints  One base class, multiple interfaces  Specified using “where” clause interface IComparable { int CompareTo(object obj); } class Dictionary class Dictionary { public void Add(K key, V value) { public void Add(K key, V value) {...... switch (((IComparable)key).CompareTo(x)) { switch (((IComparable)key).CompareTo(x)) {... }... } }} interface IComparable { int CompareTo(object obj); } class Dictionary where K: IComparable { public void Add(K key, V value) { public void Add(K key, V value) {...... switch (key.CompareTo(x)) { switch (key.CompareTo(x)) {... }... } }} interface IComparable { int CompareTo(T obj); } class Dictionary : IDictionary where K: IComparable, K: IComparable, V: IKeyProvider, V: IKeyProvider, V: IPersistable V: IPersistable {... }

32 Iterators foreach relies on “enumerator pattern” foreach relies on “enumerator pattern”  GetEnumerator() method returning object with a MoveNext() method and a Current property foreach makes enumerating easy 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);}

33 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 { List list; List list; int index; int index; object current; object current; internal ListEnumerator(List list) { internal ListEnumerator(List list) { this.list = list; this.list = list; } public bool MoveNext() { public bool MoveNext() { if (index >= list.count) { if (index >= list.count) { current = null; current = null; return false; return false; } current = list.elements[index++]; current = list.elements[index++]; return true; return true; } public object Current { public object Current { get { return current; } get { return current; } }}

34 public class List { internal object[] elements; internal object[] elements; internal int count; internal int count; public object foreach() { public object foreach() { for (int i = 0; i < count; i++) yield elements[i]; for (int i = 0; i < count; i++) yield elements[i]; }} Iterators foreach member foreach member  Logical counterpart of foreach statement yield statement yield statement  Produces next value in foreach statement public IEnumerator GetEnumerator() { return new __Enumerator(this); return new __Enumerator(this);} private class __Enumerator: IEnumerator { public bool MoveNext() { public bool MoveNext() { switch (state) { switch (state) { case 0:...; case 0:...; case 1:...; case 1:...; case 2:...; case 2:...;...... } } public T Current {...} public T Current {...}}

35 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 += new EventHandler(sender, e) { addButton.Click += new EventHandler(sender, e) { listBox.Items.Add(textBox.Text); listBox.Items.Add(textBox.Text); }; }; }}

36 Anonymous methods delegate bool Filter(object obj); public class ArrayList { public ArrayList Select(Filter matches) { public ArrayList Select(Filter matches) { ArrayList result = new ArrayList(); ArrayList result = new ArrayList(); foreach (object obj in this) { foreach (object obj in this) { if (matches(obj)) result.Add(obj); if (matches(obj)) result.Add(obj); } return result; return result; }} public class Bank { ArrayList accounts; ArrayList accounts; ArrayList GetLargeAccounts(double minBalance) { ArrayList GetLargeAccounts(double minBalance) { return accounts.Select(...); return accounts.Select(...); }} public class Bank { ArrayList accounts; ArrayList accounts; ArrayList GetLargeAccounts(double minBalance) { ArrayList GetLargeAccounts(double minBalance) { return accounts.Select(new Filter( return accounts.Select(new Filter( new MinBalanceSelector(minBalance).Matches)); new MinBalanceSelector(minBalance).Matches)); } class MinBalanceSelector class MinBalanceSelector { double minBalance; double minBalance; public MinBalanceSelector(double minBalance) { public MinBalanceSelector(double minBalance) { this.minBalance = minBalance; this.minBalance = minBalance; } public bool Matches(object obj) { public bool Matches(object obj) { return ((Account)obj).Balance >= minBalance; return ((Account)obj).Balance >= minBalance; } }} public class Bank { ArrayList accounts; ArrayList accounts; ArrayList GetLargeAccounts(double minBalance) { ArrayList GetLargeAccounts(double minBalance) { return accounts.Select( return accounts.Select( new Filter(a) { new Filter(a) { return ((Account)a).Balance >= minBalance; return ((Account)a).Balance >= minBalance; }); }); }}

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

38 C# and CLI standardization Work begun in September 2000 Work begun in September 2000  Intel, HP, IBM, Fujitsu, Plum Hall, and others ECMA standards ratified in December 2001 ECMA standards ratified in December 2001 Fast track to ISO Fast track to ISO Several CLI and C# implementations 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 Standardization of new features ongoing

39 Q & A.NET Framework SDK (includes C# compiler).NET Framework SDK (includes C# compiler)  http://msdn.microsoft.com/netframework Microsoft Visual C#.NET Microsoft Visual C#.NET  http://msdn.microsoft.com/vcsharp ECMA C# Standard ECMA C# Standard  http://www.ecma.ch/ecma1/stand/ecma-334.htm Microsoft Research Generics prototype Microsoft Research Generics prototype  http://research.microsoft.com/projects/clrgen Whitepaper on future C# language features Whitepaper on future C# language features  http://www.csharp.net NUnit unit-testing framework for.NET NUnit unit-testing framework for.NET  http://www.nunit.org


Download ppt "C#C# C#C# Kit Colbert Student Consultant representing Microsoft"

Similar presentations


Ads by Google