C#2 + C#3: Revisit And Summarize

Download as
 PPT
Presentation Description 

Microsoft provides us with new C# features so rapidly that developers  More

Views: 175
Like it  ( Likes) Dislike it  ( Dislikes)
Added: October 02, 2008 This Presentation is Public 
Presentation Category : Education All Rights Reserved
Presentation Statistics
Views on authorSTREAM: 90 | Views from Embeds: 85
- 74 views

- 4 views

- 1 views

Others - 6 views
Presentation Transcript

C#2 + C#3 :C#2 + C#3 revisit and summarize


Slide 2:generics anonymous methods partial types iterators ?? operator #pragma warning directives friend assemblies static classes closures generic delegation tuples comparisons type/collection initializers property access modifiers lazy evaluation lambda expressions anonymous types extension methods auto implemented properties pipeline pattern partial methods type inference extensibility code generation nullable types namespace alias qualifier expression trees implicit typing helpers fluent interfaces decorator pattern


Slide 4:string[] list = {"one", "two", "three"}; foreach (string item in list) { Console.WriteLine(item); }


Slide 5:string[] list = {"one", "two", "three"}; IEnumerator i = list.GetEnumerator(); while (i.MoveNext()) { Console.WriteLine(i.Current); }


Slide 6:class Foo { public Boo GetEnumerator() { return new Boo(); } public struct Boo { public bool MoveNext() { ... } public object Current { ... } } } Foo foo = new Foo(); foreach (object i in foo) { ... }


duck typing: collection initializers :duck typing: collection initializers


Slide 8:private static readonly List defaults = new List { new FavoriteBeer ("Bernard", "Černy"), new FavoriteBeer ("Staropramen", "Granat"), new FavoriteBeer ("Velvet", null) } class BeerCollection : List { public void Add(string name, string type) { Add(new FavoriteBeer(name, type)); } } private static readonly BeerCollection defaults = new BeerCollection { {"Bernard", "Černy"}, {"Staropramen", "Granat"}, {"Velvet", null} }


Forbid collection initializing :Forbid collection initializing ? Enforce collection initializing ?


Slide 11:public class UppercaseStrings : IEnumerable { private string[] items = null; public UppercaseStrings (string[] parms) { ... } IEnumerator IEnumerable.GetEnumerator() { return new StringEnumerator(this); } public IEnumerator GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } public struct ToUpperEnumerator : IEnumerator { ... } }


Slide 12:public struct ToUpperEnumerator : IEnumerator { private int index; private UppercaseStrings collection; internal ToUpperEnumerator(UppercaseStrings strings) { collection = strings; index = -1; } public bool MoveNext() { return (++index .Current { get { return collection.items[index].ToUpper(); } } public object Current { get { return ((IEnumerator) this).Current; } } public void Reset() { index = -1; } public void Dispose() { //do nothing } }


Slide 13:public class UppercaseStrings : IEnumerable { private string[] items = null; public UppercaseStrings (string[] parms) { ... } IEnumerator IEnumerable.GetEnumerator() { return new ToUpperEnumerator(this); } public IEnumerator GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } ... }


Slide 14:public class UppercaseStrings : IEnumerable { private string[] items = null; public UppercaseStrings (string[] parms) { ... } IEnumerator IEnumerable.GetEnumerator() { for (int i = 0; i )this).GetEnumerator(); } ... }


Slide 17:public class Node { public readonly T Item; public readonly Node Left; public readonly Node Right; public Node(T item, Node left, Node right) { Item = item; Left = left; Right = right; } } A E C B D


Asymptotic analysis :Asymptotic analysis time, O(n) O(n) O(log n) amount of elements, n O(n2)


Slide 19:1 5 3 2 4 6 n h … O(h) O(n*h) log n ≤ h ≤ n O(nlog n) ≤ complexity ≤ O(n2)


pipeline pattern :pipeline pattern


var :var


use it, if you want… :use it, if you want…


but in small chunks of code :but in small chunks of code


Slide 24:using(MyPresentationSummary summary = MyPresentationSummary.Create()) { } using(var summary = MyPresentationSummary.Create()) { } MyPresentationSummary summary = new MyPresentationSummary (); var summary = new MyPresentationSummary(); Assembly1.Action action1 = GetAction(); … Assembly2.Action action2 = GetCompletelyDifferentAction(); var action1 = GetAction(); … var action2 = GetCompletelyDifferentAction(); //another assembly


Slide 25:you’re forced to initialize a variable to a non-null value, and it makes you think better about the naming, and it removes code noise and so on


Slide 26:var summary = GetPresentation(); var summary = GetPresentationSummary(); var size = GetSize(); int size = GetSize(); var cmdDetails = GetDetails(); var details = GetDetails();


anonymous types :anonymous types var query = from c in customers select new { c.Name, c.City };


Slide 28:var i = new { Name = "Foo", City = "Boo" };


Slide 29:var a = new { A = "Foo", B = 12 }; var b = new { A = DateTime.MinValue, B = false }; ILDASM.EXE


Slide 30:public static bool IsAnonymous(Type type) { Type generated = typeof(CompiterGeneratedAttribute); TypeAttributes notPublic = TypeAttributes.NotPublic; TypeAttributes isSealed = TypeAttributes.Sealed; return type.IsGenericType && Attribute.IsDefined(type, generated) && (type.Attributes & notPublic) == notPublic && (type.Attributes & isSealed) == isSealed; && type.Name.Contains("AnonymousType") }


anonymous methods :anonymous methods


Slide 32:btnSubmit.Click += delegate (object sender, EventArgs e) { MessageBox.Show("Hi there"); };


Slide 33:Predicate Converter Action Comparison


anonymous methods, :anonymous methods, “normal” methods, …


Slide 36:public delegate TResult Func(); public delegate TResult Func(T p); public delegate TResult Func(T1 p1, T2 p2); ... (up to 4 parameters) public delegate void Action(); public delegate void Action(T p); public delegate void Action(T1 p1, T2 p2); ... (up to 4 parameters)


why? :why?


Slide 38:var f = (() => 5); //would not compile Func f = (() => new { Name = "foo"}); var f = (() => 5); //would not compile Func f = (() => 5); //ok Func Lambda(Func lambda) { return lambda; } ... var f = Lambda(() => new { Name = "foo"}); Console.WriteLine(f().Name);


Null coalescing operator :string a = "hi there"; string b = a ?? "got null"); //hi there string a = null; string b = a ?? "got null"); //got null int? a = null; int result = a ?? 0; //result = 0 Null coalescing operator Customer c = GetCustomer(); return (c != null) ? c : new Customer(); Customer c = GetCustomer(); return c ?? new Customer(); return GetCustomer() ?? new Customer();


Slide 40:Expression trees


Slide 42:Expression a = Expression.Constant(2); Expression b = Expression.Constant(3); Expression c = Expression.Add(a, b); var add = Expression.Lambda>(c).Compile(); Console.WriteLine(add());


Slide 43:void Call(Expression> action) where T : new() { string name = ((MethodCallExpression)action.Body).Method.Name; MethodInfo method = typeof(T).GetMethod(name); method.Invoke(new T(), null); } //instead of passing a string name, pass a strongly typed lambda Call(c => c.Summary());


Slide 44:© unknown


Slide 45:© Jeffrey Vanhoutte


Slide 46:© Hernan Churba


functional? :functional?


readability! :readability! maintainability!


Slide 49:interface IDeveloper { void WriteCode(); void ReadMsdn(); } interface IPerson { void DrinkBeer(); } internal partial Somebody : IDeveloper, IPerson { ... }


refactoring :refactoring


keep huge types? :keep huge types? (are you kidding?)


Slide 53:partial class Customer { public string Name { get {...} set { OnNameChanging(value); _name = value; OnNameChanged(); } } partial void OnNameChanging(string name); partial void OnNameChanged(); }


static classes :static classes extension methods


Slide 55:public sealed class Foo { private Foo() { } public static void Boo() { } //other static members } public static class Foo { public static void Boo() { } //other static members } .NET 1.0: System.Environment.HasShutdownStarted


Slide 56:Presentation.From("Andrew") .About("C#") .On(1.October(2008)) .At(6.OClock()); Presentation.From("Andrew") .About("C#") .On(1.October(2008)) .At(6.OClock()) .AlmostFinished(":)");


Slide 57:public static class DateExtensions { public static DateTime October(this int day, int year) { return new DateTime(year, 10, day); } }


Slide 59:separate namespace simplicity periodical review


Slide 60:[assembly:InternalsVisibleTo("FriendAssembly, PublicKey=…" )] System.Data System.Web System.Data.Entity System.Web.Extensions


Slide 61:public void Test { int a = 0; } public void Test { #pragma warning disable 219 int a = 0; #pragma warning restore 219 }


http://codevanced.net :http://codevanced.net


The End :The End