39
C # Kit Colbert Kit Colbert Student Consultant representing Microsoft Student Consultant representing Microsoft [email protected] [email protected]

C#C# C#C# Kit Colbert Student Consultant representing Microsoft [email protected]

  • View
    218

  • Download
    1

Embed Size (px)

Citation preview

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

C#C#Kit ColbertKit ColbertStudent Consultant representing MicrosoftStudent Consultant representing [email protected]@brown.edu

Page 2: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

C#C#

Design goalsDesign goals Unified type systemUnified type system Component-oriented featuresComponent-oriented features Productivity featuresProductivity features C# futuresC# futures StandardizationStandardization

Page 3: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

C# design goalsC# design goals

Dramatically increase productivityDramatically increase productivity Provide unified and extensible type Provide unified and extensible type

systemsystem Support component-oriented Support component-oriented

programmingprogramming Enable robust and durable Enable robust and durable

applicationsapplications Build foundation for future innovationBuild foundation for future innovation

Page 4: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Unified type systemUnified type system

Traditional views of primitive typesTraditional views of primitive types C++, Java: They’re “special”C++, Java: They’re “special” Smalltalk, Lisp: They’re full-blown Smalltalk, Lisp: They’re full-blown

objectsobjects C# unifies with no performance costC# unifies with no performance cost

Value types, boxing and unboxingValue types, boxing and unboxing Deep simplicity throughout systemDeep simplicity throughout system

Improved extensibility and Improved extensibility and reusabilityreusability New primitive types: Decimal, SQL…New primitive types: Decimal, SQL… Collections, etc., work for all typesCollections, etc., work for all types

Page 5: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Value and reference typesValue and reference types

Value typesValue types Variables directly contain dataVariables directly contain data Cannot be nullCannot be null

Reference typesReference types Variables contain references to objectsVariables contain references to objects May be nullMay be null

int i = 123;int i = 123;string s = "Hello world";string s = "Hello world";123123ii

ss "Hello world""Hello world"

Page 6: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Value and reference typesValue and reference types

Value typesValue types PrimitivesPrimitives int i; double x;int i; double x; EnumsEnums enum State { Off, On }enum State { Off, On } StructsStructs struct Point { int x, y; }struct Point { int x, y; }

Reference typesReference types ClassesClasses class Foo: Bar, IFoo {...}class Foo: Bar, IFoo {...} InterfacesInterfaces interface IFoo: IBar {...}interface IFoo: IBar {...} ArraysArrays Foo[] a = new Foo[10];Foo[] a = new Foo[10]; DelegatesDelegates delegate void Empty();delegate void Empty();

Page 7: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

ClassesClasses

InheritanceInheritance Single base class (System.Object)Single base class (System.Object) Multiple interface implementationsMultiple interface implementations

Class membersClass members Static and instance membersStatic and instance members Nested typesNested types

Member accessMember access Public, protected, internal, privatePublic, protected, internal, private

Page 8: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

StructsStructs

Like classes, exceptLike classes, except Stored in-line, not heap allocatedStored in-line, not heap allocated Assignment copies data, not referenceAssignment copies data, not reference Always inherit directly from Always inherit directly from

System.ObjectSystem.Object Ideal for light weight objectsIdeal for light weight objects

Complex, Point, Rectangle, ColorComplex, Point, Rectangle, Color int, float, double, etc., are all structsint, float, double, etc., are all structs

No heap allocation, less GC pressureNo heap allocation, less GC pressure More efficient use of memoryMore efficient use of memory

Page 9: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Classes and structsClasses and structs

class CPoint { int x, y; ... }class CPoint { int x, y; ... }struct SPoint { int x, y; ... }struct SPoint { int x, y; ... }

CPoint cp = new CPoint(10, 20);CPoint cp = new CPoint(10, 20);SPoint sp = new SPoint(10, 20);SPoint sp = new SPoint(10, 20);

1010

2020spsp

cpcp

1010

2020

CPointCPoint

Page 10: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Unified type systemUnified type system

BoxingBoxing Allocates box, copies value into itAllocates box, copies value into it

UnboxingUnboxing Checks type of box, copies value outChecks type of box, copies value out

int i = 123;int i = 123;object o = i;object o = i;int j = (int)o;int j = (int)o;

123123i

o

123123

System.Int32System.Int32

123123j

Page 11: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Unified type systemUnified type system

Several benefitsSeveral benefits Eliminates “wrapper classes”Eliminates “wrapper classes” Collection classes work with all typesCollection classes work with all types

Lots of examples in .NET FrameworkLots of examples in .NET Frameworkstring s = string.Format(string s = string.Format( "On {0} your balance was {1}", date, balance);"On {0} your balance was {1}", date, balance);

Hashtable t = new Hashtable();Hashtable t = new Hashtable();t.Add(0, "zero");t.Add(0, "zero");t.Add(1, "one");t.Add(1, "one");t.Add(2, "two");t.Add(2, "two");

Page 12: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Component-oriented Component-oriented featuresfeatures What defines a component?What defines a component?

Properties, methods, events, attributesProperties, methods, events, attributes C# has first class supportC# has first class support

Not naming patterns, adapters, etc.Not naming patterns, adapters, etc. Not external filesNot external files

Components are easy to build and Components are easy to build and consumeconsume

Page 13: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

PropertiesProperties

First class language constructFirst class language construct

public class Button: Controlpublic 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();Button b = new Button();b.Text = "OK";b.Text = "OK";string s = b.Text;string s = b.Text;

Page 14: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

EventsEvents

First class language constructFirst class language construct

public delegate void EventHandler(public delegate void EventHandler( object sender, EventArgs e);object sender, EventArgs e);

public class Button: Controlpublic class Button: Control{{ public event EventHandler Click; public event EventHandler Click;

protected void OnClick(EventArgs e) {protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); if (Click != null) Click(this, e); } }}}

void Initialize() {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) {void ButtonClick(object sender, EventArgs e) { MessageBox.Show("You pressed the button");MessageBox.Show("You pressed the button");}}

Page 15: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

AttributesAttributes

How do you associate information How do you associate information with types and members?with types and members? Category of a propertyCategory of a property Transaction context for a methodTransaction context for a method XML persistence mappingXML persistence mapping

Traditional solutionsTraditional solutions Add keywords or pragmas to languageAdd keywords or pragmas to language Use external files (e.g., .IDL, .DEF)Use external files (e.g., .IDL, .DEF)

C# solution: AttributesC# solution: Attributes

Page 16: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

AttributesAttributespublic class Button: Controlpublic 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.Attributepublic 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);Type type = typeof(Button);foreach (Attribute a in type.GetCustomAttributes()) {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); }}}}

Page 17: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

AttributesAttributes

Completely extensibleCompletely extensible New attributes are created by inheriting New attributes are created by inheriting

from System.Attributefrom System.Attribute Type-safeType-safe

Arguments checked at compile-timeArguments checked at compile-time Examined using reflection at run-timeExamined using reflection at run-time

Extensive use in .NET frameworksExtensive use in .NET frameworks XML, Web Services, security, XML, Web Services, security,

serialization, component model, COM serialization, component model, COM and P/Invoke interop, code and P/Invoke interop, code configuration…configuration…

Page 18: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Productivity featuresProductivity features

parameter arraysparameter arrays ref and out parametersref and out parameters overflow checkingoverflow checking foreach statementforeach statement using statementusing statement switch on stringswitch on string

Page 19: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Parameter arraysParameter arrays

Can write “printf” style methodsCan write “printf” style methods Type-safe, unlike C++Type-safe, unlike C++

static void printf(string fmt, static void printf(string fmt, paramsparams object[] args) { object[] args) { foreach (object x in args) {foreach (object x in args) { ...... }}}}

printf("%s %i", s, i);printf("%s %i", s, i);

object[] args = new object[2];object[] args = new object[2];args[0] = s;args[0] = s;args[1] = i;args[1] = i;printf("%s %i", args);printf("%s %i", args);

Page 20: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

ref and out parametersref and out parameters

Use “ref” for in/out parameter Use “ref” for in/out parameter passingpassing

Use “out” to return multiple valuesUse “out” to return multiple values Must repeat ref/out at call siteMust repeat ref/out at call sitestatic void Swap(static void Swap(refref int a, int a, refref int b) {...} int b) {...}

static void Divide(int dividend, int divisor,static void Divide(int dividend, int divisor, outout int result, int result, outout int remainder) {...} int remainder) {...}

static void Main() {static void Main() { int x = 1, y = 2;int x = 1, y = 2; Swap(Swap(refref x, x, refref y); y);}}

Page 21: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Overflow checkingOverflow checking

Integer arithmetic operationsInteger arithmetic operations C, C++, Java silently overflowC, C++, Java silently overflow

checked vs. unchecked contextschecked vs. unchecked contexts Default is unchecked, except for Default is unchecked, except for

constantsconstants Change with “/checked” compiler switchChange with “/checked” compiler switch

int i = int i = checkedchecked(x * y);(x * y);

checkedchecked { { int i = x * y;int i = x * y;}}

Page 22: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

foreach statementforeach statement

Iteration of arraysIteration of arrays

Iteration of IEnumerable collectionsIteration of IEnumerable collectionsArrayList accounts = Bank.GetAccounts(...);ArrayList accounts = Bank.GetAccounts(...);foreachforeach (Account a in accounts) { (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) {public static void Main(string[] args) { foreachforeach (string s in args) Console.WriteLine(s); (string s in args) Console.WriteLine(s);}}

Page 23: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

using statementusing statement

static void Copy(string sourceName, string destName) {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) {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) {static void Copy(string sourceName, string destName) { usingusing (Stream input = File.OpenRead(sourceName)) (Stream input = File.OpenRead(sourceName)) usingusing (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); }} }}}}

Page 24: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

using statementusing statement

Acquire, Execute, Release patternAcquire, Execute, Release pattern Works with any IDisposable objectWorks with any IDisposable object

Data access classes, streams, text Data access classes, streams, text readers and writers, network classes, readers and writers, network classes, etc.etc.

using (Resource res = new Resource()) {using (Resource res = new Resource()) { res.DoWork();res.DoWork();}}

Resource res = new Resource(...);Resource res = new Resource(...);try {try { res.DoWork();res.DoWork();}}finally {finally { if (res != null) ((IDisposable)res).Dispose();if (res != null) ((IDisposable)res).Dispose();}}

Page 25: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Switch on stringSwitch on string

Color ColorFromFruit(string s) {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(); }}}}

Page 26: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

C# futuresC# futures

GenericsGenerics IteratorsIterators Anonymous methodsAnonymous methods Partial typesPartial types

Page 27: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

public class Listpublic 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; } }}}}

GenericsGenericspublic class Listpublic class List<ItemType><ItemType>{{ private private ItemTypeItemType[] elements;[] elements; private int count;private int count;

public void Add(public void Add(ItemTypeItemType element) { element) { if (count == elements.Length) Resize(count * 2);if (count == elements.Length) Resize(count * 2); elements[count++] = element;elements[count++] = element; }}

public public ItemTypeItemType this[int index] { 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();List intList = new List();

intList.Add(1);intList.Add(1);intList.Add(2);intList.Add(2);intList.Add("Three");intList.Add("Three");

int i = (int)intList[0];int i = (int)intList[0];

List intList = new List();List intList = new List();

intList.Add(1); // Argument is boxedintList.Add(1); // Argument is boxedintList.Add(2); // Argument is boxedintList.Add(2); // Argument is boxedintList.Add("Three"); // Should be an errorintList.Add("Three"); // Should be an error

int i = (int)intList[0]; // Cast requiredint i = (int)intList[0]; // Cast required

ListList<int><int> intList = new List intList = new List<int><int>();();

intList.Add(1); // No boxingintList.Add(1); // No boxingintList.Add(2); // No boxingintList.Add(2); // No boxingintList.Add("Three"); // Compile-time errorintList.Add("Three"); // Compile-time error

int i = intList[0]; // No cast requiredint i = intList[0]; // No cast required

Page 28: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

GenericsGenerics

Why generics?Why generics? Compile-time type checkingCompile-time type checking Performance (no boxing, no downcasts)Performance (no boxing, no downcasts) Reduced code bloat (typed collections)Reduced code bloat (typed collections)

C# generics vs. C++ templatesC# generics vs. C++ templates C# generics are checked at declarationC# generics are checked at declaration C# generics are instantiated at run-C# generics are instantiated at run-

timetime C# generics vs. proposed Java C# generics vs. proposed Java

genericsgenerics C# generics work over entire type C# generics work over entire type

systemsystem C# generics preserve types at run-timeC# generics preserve types at run-time

Page 29: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

GenericsGenerics

Type parameters can be applied toType parameters can be applied to Class, struct, interface, and delegate Class, struct, interface, and delegate

typestypesclass Dictionary<KeyType, ValueType> {...}class Dictionary<KeyType, ValueType> {...}

struct Pair<FirstType, SecondType> {...}struct Pair<FirstType, SecondType> {...}

interface IComparer<T> {...}interface IComparer<T> {...}

delegate ResType Func<ArgType, ResType>(ArgType arg);delegate ResType Func<ArgType, ResType>(ArgType arg);Dictionary<string, Customer> customerLookupTable;Dictionary<string, Customer> customerLookupTable;

Dictionary<string, List<Order>> orderLookupTable;Dictionary<string, List<Order>> orderLookupTable;

Dictionary<int, string> numberSpellings;Dictionary<int, string> numberSpellings;

Page 30: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

GenericsGenerics

Type parameters can be applied toType parameters can be applied to Class, struct, interface, and delegate Class, struct, interface, and delegate

typestypes MethodsMethods

class Arrayclass Array{{ public static T[] Create<T>(int size) {public static T[] Create<T>(int size) { return new T[size];return new T[size]; }}

public static void Sort<T>(T[] array) {public static void Sort<T>(T[] array) { ...... }}}}

string[] names = Array.Create<string>(3);string[] names = Array.Create<string>(3);names[0] = "Jones";names[0] = "Jones";names[1] = "Anderson";names[1] = "Anderson";names[2] = "Williams";names[2] = "Williams";Array.Sort(names);Array.Sort(names);

Page 31: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

GenericsGenerics

ConstraintsConstraints One base class, multiple interfacesOne base class, multiple interfaces Specified using “where” clauseSpecified using “where” clause

interface IComparable { int CompareTo(object obj); }interface IComparable { int CompareTo(object obj); }

class Dictionary<K, V>class Dictionary<K, V>{{ public void Add(K key, V value) {public void Add(K key, V value) { ...... switch (switch (((IComparable)key).CompareTo(x)((IComparable)key).CompareTo(x)) {) { ...... } } }}}}

interface IComparable { int CompareTo(object obj); }interface IComparable { int CompareTo(object obj); }

class Dictionary<K, V> class Dictionary<K, V> where K: IComparablewhere K: IComparable{{ public void Add(K key, V value) {public void Add(K key, V value) { ...... switch (switch (key.CompareTo(x)key.CompareTo(x)) {) { ...... } } }}}}

interface IComparable<T> { int CompareTo(T obj); }interface IComparable<T> { int CompareTo(T obj); }

class Dictionary<K, V>: IDictionary<K, V> class Dictionary<K, V>: IDictionary<K, V> wherewhere K: IComparable<K>,K: IComparable<K>, V: IKeyProvider<K>,V: IKeyProvider<K>, V: IPersistableV: IPersistable{{ ... ...}}

Page 32: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

IteratorsIterators

foreach relies on “enumerator foreach relies on “enumerator pattern”pattern” GetEnumerator() method returning GetEnumerator() method returning

object with a MoveNext() method and a object with a MoveNext() method and a Current propertyCurrent property

foreach makes enumerating easyforeach makes enumerating easy But enumerators are hard to write!But enumerators are hard to write!foreach (object obj in list) {foreach (object obj in list) {

DoSomething(obj);DoSomething(obj);}}

Enumerator e = list.GetEnumerator();Enumerator e = list.GetEnumerator();while (e.MoveNext()) {while (e.MoveNext()) { object obj = e.Current;object obj = e.Current; DoSomething(obj);DoSomething(obj);}}

Page 33: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

IteratorsIterators

public class Listpublic class List{{ internal object[] elements;internal object[] elements; internal int count;internal int count;

public ListEnumerator GetEnumerator() {public ListEnumerator GetEnumerator() { return new ListEnumerator(this); return new ListEnumerator(this); }}}}

public class ListEnumeratorpublic 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; } }}}}

Page 34: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

public class Listpublic class List{{ internal object[] elements;internal object[] elements; internal int count;internal int count;

public object public object foreach()foreach() { { for (int i = 0; i < count; i++) for (int i = 0; i < count; i++) yieldyield elements[i]; elements[i]; }}}}

IteratorsIterators

foreach memberforeach member Logical counterpart of foreach Logical counterpart of foreach

statementstatement yield statementyield statement

Produces next value in foreach Produces next value in foreach statementstatement

public IEnumerator<T> GetEnumerator() {public IEnumerator<T> GetEnumerator() { return new __Enumerator(this);return new __Enumerator(this);}}

private class __Enumerator: IEnumerator<T>private class __Enumerator: IEnumerator<T>{{ 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 {...}}}

Page 35: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Anonymous methodsAnonymous methodsclass MyForm: Formclass 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: Formclass 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); };}; }}}}

Page 36: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Anonymous methodsAnonymous methodsdelegate bool Filter(object obj);delegate bool Filter(object obj);

public class ArrayListpublic 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 Bankpublic class Bank{{ ArrayList accounts;ArrayList accounts;

ArrayList GetLargeAccounts(double minBalance) {ArrayList GetLargeAccounts(double minBalance) { return accounts.Select(...);return accounts.Select(...); }}}}

public class Bankpublic 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 MinBalanceSelectorclass 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 Bankpublic 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; });}); }}}}

Page 37: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Partial typesPartial typespublic public partialpartial class Customer class Customer{{ private int id;private int id; private string name;private string name; private string address;private string address; private List<Orders> orders;private List<Orders> orders;}}

public public partialpartial class Customer 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 Customerpublic class Customer{{ private int id;private int id; private string name;private string name; private string address;private string address; private List<Orders> orders;private List<Orders> 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; }}}}

Page 38: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

C# and CLI C# and CLI standardizationstandardization Work begun in September 2000Work begun in September 2000

Intel, HP, IBM, Fujitsu, Plum Hall, and Intel, HP, IBM, Fujitsu, Plum Hall, and othersothers

ECMA standards ratified in December ECMA standards ratified in December 20012001

Fast track to ISOFast track to ISO Several CLI and C# implementationsSeveral CLI and C# implementations

.NET Framework and Visual Studio .NET.NET Framework and Visual Studio .NET ““SSCLI” – Shared source on XP, FreeBSD, SSCLI” – Shared source on XP, FreeBSD,

OS XOS X ““Mono” – Open source on LinuxMono” – Open source on Linux

Standardization of new features Standardization of new features ongoingongoing

Page 39: C#C# C#C# Kit Colbert Student Consultant representing Microsoft mssc@brown.edu

Q & AQ & A .NET Framework SDK (includes C# .NET Framework SDK (includes C#

compiler)compiler) http://msdn.microsoft.com/netframeworkhttp://msdn.microsoft.com/netframework

Microsoft Visual C# .NETMicrosoft Visual C# .NET http://msdn.microsoft.com/vcsharphttp://msdn.microsoft.com/vcsharp

ECMA C# StandardECMA C# Standard http://www.ecma.ch/ecma1/stand/ecma-http://www.ecma.ch/ecma1/stand/ecma-

334.htm334.htm Microsoft Research Generics prototypeMicrosoft Research Generics prototype

http://research.microsoft.com/projects/clrgenhttp://research.microsoft.com/projects/clrgen Whitepaper on future C# language Whitepaper on future C# language

featuresfeatures http://www.csharp.nethttp://www.csharp.net

NUnit unit-testing framework for .NETNUnit unit-testing framework for .NET http://www.nunit.orghttp://www.nunit.org