PowerPoint Presentation C# Advanced features Feb 2016 Agenda Automatic type, property Object & Collection initializer Anonymous type, method Delegate & event, polymorphism Reference Miscellaneous Auto[.]
Trang 1C# Advanced
features
Feb 2016
Trang 21 Automatic: type, property
2 Object & Collection initializer
3 Anonymous: type, method
4 Delegate & event, polymorphism
5 Reference
6 Miscellaneous
Trang 3Automatic type & property
1
Trang 53 What is the benefit?
4 Why would developer want to use it?
Actually, when to use and when not to use?
Trang 6My best usage scenario
List declaration
List iteration
Trang 7Later usage in this
course
Trang 8Automatic property
OOP encapsulation rule
Never expose public fields, use property instead!
Better for logic adding later
No breaking changes! => Better maintenance
Properties can be databound, fields cannot!
Trang 9Equivalent
Whatever you write, the right code will
always be generated! (Kind of similarity, not exactly)
Trang 11Read only property
Lúc trước
public string FirstName { get; private set; }
public string LastName { get; private set; }
Bản mới
public string FirstName { get; }
public string LastName { get; }
Trang 12Object & Collection initializer
2
Trang 13Object initializer
Old way to initialize
New and more convenient way to initialize
Trang 14Collection initializer
Trang 15Anonymous type & method
3
Trang 16Things to consider
Same class?
Trang 17Anonymous type
Usage scenario: purely for storing data
(database access)
Trang 18Delegate & event
4
Trang 20Delegate example
Trang 21Event
Like Win32 API callback
Register function that will be called when an
event happen
Trang 22Event example
Trang 23Usage scenario
Create processing framework
Generalization
Trang 24Lambda expression
Trang 25Func<in T, out TResult>
Trang 26Example – Sort method
How to make it work with any type rather
than int?
Trang 27Solution
Trang 285
Trang 29Question 1: result?
Trang 30Question 2: result
Trang 31Given a Cat class
Trang 32Question 3: result?
Trang 33Question 4: result?
Do we still have the old cat?
Trang 34Question 5: result?
Do we still have the old cat?
Trang 35Weak reference
Trang 3636
Trang 37Extension methods
String fox = “fox”; fox.GetWordCount();
Trang 38 Be carefull of this type of unsafe code!
Cannot free the memory
Automatically delete after method ends
Trang 39Generics vs ArrayList
Classes & Methods independent of
contained types
List, Queue, Stack, Array…
Can be Delegates, Lambdas, Events
Vs ArrayList
Trang 40yield return
yield break: stop iteration
Trang 41Tuple
Trang 42checked & unchecked
checked: forced overflow checking, throw
OverflowException
Trang 43is & as operator
is: checking type
as: safe type casting