Introduction to C# 2.0Introduction to C# 2.0
An Advanced Look
Adam CalderonAdam CalderonPrincipal Engineer - InterknowlogyPrincipal Engineer - InterknowlogyMicrosoft MVP – C#Microsoft MVP – C#
AgendaAgenda
Static ClassesStatic ClassesGenericsGenericsPartial TypesPartial TypesAnonymous MethodsAnonymous MethodsIteratorsIteratorsNamespace Alias QualifierNamespace Alias QualifierProperty Accessor AccessibilityProperty Accessor Accessibility
Static ClassesStatic Classes
Can contain only static membersCan contain only static membersNo instance membersNo instance members
public public staticstatic class Math 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) {…} … …}}
GenericsGenericsWhy generics?Why generics?
Type checking, no boxing, no downcastsType checking, no boxing, no downcastsReduced code bloat (typed collections)Reduced code bloat (typed collections)
How are C# generics implemented?How are C# generics implemented?Instantiated at run-time, not compile-timeInstantiated at run-time, not compile-timeChecked at declaration, not instantiationChecked at declaration, not instantiationWork for both reference and value typesWork for both reference and value typesComplete run-time type informationComplete run-time type information
How are they used?How are they used?
Can be used with various typesCan be used with various typesClass, struct, interface and delegateClass, struct, interface and delegate
Can be used with methods, parameters and return Can be used with methods, parameters and return typestypesSupport the concept of constraintsSupport the concept of constraints
One base class, multiple interfaces, new()One base class, multiple interfaces, new()
class Dictionaryclass Dictionary<K,V><K,V> {…} {…}
struct HashBucketstruct HashBucket<K,V><K,V> {…} {…}
interface IComparerinterface IComparer<T><T> {…} {…}
delegate R Functiondelegate R Function<A,R><A,R>(A arg);(A arg);
class Utilsclass Utils{{ public static public static TT[] CreateArray(int size) {[] CreateArray(int size) { return new return new TT[size];[size]; }}
public static void SortArraypublic static void SortArray<T><T>((TT[] array) {[] array) { … … }}}}
class Dictionaryclass Dictionary<K,V><K,V>: IDictionary: IDictionary<K,V><K,V> where where KK: IComparable: IComparable<K><K> where where VV: IKeyProvider: IKeyProvider<K><K>, IPersistable, new(), IPersistable, new(){{ public void Add(K key, V value) { public void Add(K key, V value) { … … }}}}
Generic Collections and Generic Collections and InterfacesInterfaces
System.Collections.Generic classesSystem.Collections.Generic classesList<ItemType>List<ItemType>Dictionary<K,V>Dictionary<K,V>Stack<ItemType>Stack<ItemType>Queue<ItemType>Queue<ItemType>
System.Collections.Generic System.Collections.Generic interfacesinterfaces
IList<ItemType>IList<ItemType>IDictionary<K,V>IDictionary<K,V>ICollection<ItemType>ICollection<ItemType>IEnumerable<ItemType>IEnumerable<ItemType>IEnumerator<ItemType>IEnumerator<ItemType>IComparable<OperandType>IComparable<OperandType>IComparer<OperandType>IComparer<OperandType>
Various other Generic Various other Generic ClassesClasses
System.Collections.ObjectModel System.Collections.ObjectModel classesclasses
Collection<T>Collection<T>KeyedCollection<T>KeyedCollection<T>ReadOnlyCollection<T>ReadOnlyCollection<T>
Various Other ClassesVarious Other ClassesNullable<T>Nullable<T>EventHandler<T>EventHandler<T>Comparer<T>Comparer<T>
GenericsGenerics
Introduction to C# 2.0Introduction to C# 2.0
Partial TypesPartial Types
Ability to break up declaration into Ability to break up declaration into multiple filesmultiple filesTypes supportedTypes supported
ClassesClassesStructStructInterfaceInterface
Partial ClassesPartial Classes
public partial class Customerpublic partial 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 partial class Customerpublic 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 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; }}}}
Anonymous MethodsAnonymous Methods
Allows code block in place of delegateAllows code block in place of delegateDelegate type automatically inferredDelegate type automatically inferred
Code block can be parameterlessCode block can be parameterlessOr code block can have parametersOr code block can have parametersIn either case, return types must matchIn either case, return types must match
button.Click += delegate { MessageBox.Show("Hello"); };button.Click += delegate { MessageBox.Show("Hello"); };
button.Click += delegate(object sender, EventArgs e) {button.Click += delegate(object sender, EventArgs e) { MessageBox.Show(((Button)sender).Text); MessageBox.Show(((Button)sender).Text);};};
Anonymous MethodsAnonymous Methods
int int nn = 0; = 0;Del d = delegate() { System.Console.WriteLine("Copy #:{0}", +Del d = delegate() { System.Console.WriteLine("Copy #:{0}", +++nn); };); };
Code block can access local variablesCode block can access local variablesLifetime of the outer variable extends Lifetime of the outer variable extends until the delegates that reference the until the delegates that reference the anonymous methods are eligible for anonymous methods are eligible for garbage collectiongarbage collectionCode block cannot access the ref or Code block cannot access the ref or out parameters of an outer scope.out parameters of an outer scope.
Anonymous MethodsAnonymous Methods
Introduction to C# 2.0Introduction to C# 2.0
IteratorsIterators
foreach relies on “enumerator foreach relies on “enumerator pattern”pattern”
GetEnumerator() methodGetEnumerator() method
foreach makes enumerating easyforeach makes enumerating easyBut 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);}}
IteratorsIterators
Method that incrementally computes Method that incrementally computes and returns a sequence of valuesand returns a sequence of values
yield return and yield breakyield return and yield breakMust return IEnumerator or IEnumerableMust return IEnumerator or IEnumerable
Method that incrementally computes Method that incrementally computes and returns a sequence of valuesand returns a sequence of values
yield return and yield breakyield return and yield breakMust return IEnumerator or IEnumerableMust return IEnumerator or IEnumerable
public class Listpublic 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];yield return elements[i]; }} }}}}
IteratorsIterators
public class List<T>public class List<T>{{ public IEnumerator<T> GetEnumerator() {public IEnumerator<T> 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<T> Descending() {public IEnumerable<T> 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<T> Subrange(int index, int n) {public IEnumerable<T> 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]; }}}} List<Item> items = GetItemList();List<Item> items = GetItemList();
foreach (Item x in items) {…}foreach (Item x in items) {…}foreach (Item x in items.Descending()) {…}foreach (Item x in items.Descending()) {…}foreach (Item x in Items.Subrange(10, 20)) {…}foreach (Item x in Items.Subrange(10, 20)) {…}
IteratorsIterators
Introduction to C# 2.0Introduction to C# 2.0
Namespace Alias QualifierNamespace Alias Qualifier
A::B looks up A only as namespace A::B looks up A only as namespace aliasaliasglobal::X starts lookup in global global::X starts lookup in global namespacenamespace
using IO = System.IO;using IO = System.IO;
class Programclass Program{{ static void Main() {static void Main() { IO::StreamIO::Stream s = new IO::File.OpenRead("foo.txt"); s = new IO::File.OpenRead("foo.txt"); global::Systemglobal::System.Console.WriteLine("Hello");.Console.WriteLine("Hello"); }}
Property Accessor Property Accessor AccessibilityAccessibility
Allows one accessor to be restricted furtherAllows one accessor to be restricted furtherTypically set {…} more restricted than get {…}Typically set {…} more restricted than get {…}
public class Customerpublic class Customer{{ private string id;private string id;
public string CustomerId {public string CustomerId { get { return id; }get { return id; } internalinternal set { id = value; } set { id = value; } }}}}
ResourcesResources
Links
http://msdn.microsoft.com/vcsharp/
http://msdn.microsoft.com/vcsharp/programming/language/
http://www.csharp-corner.com/
Books
Programming Microsoft Visual C# 2005, The Language
The C# Programming Language
Adam CalderonAdam Calderon
More info on InterKnowlogyMore info on InterKnowlogywww.InterKnowlogy.comwww.InterKnowlogy.com
Contact InformationContact InformationE-mail: E-mail: [email protected]@InterKnowlogy.comPhone: Phone: 760-930-0075 x274760-930-0075 x274Blog: Blog:
http://blogs.InterKnowlogy.com/AdamCalderonhttp://blogs.InterKnowlogy.com/AdamCalderon
About Adam CalderonAbout Adam CalderonMicrosoftMicrosoft®® MVP – C# MVP – C#MicrosoftMicrosoft®® UI Server Frameworks Advisory UI Server Frameworks Advisory CouncilCouncilDeveloper / Author / SpeakerDeveloper / Author / Speaker