Advanced C#
Delegates• We can use interfaces instead of
delegates.• Delegates – we need it to separate
implementation and interface.
Anonymous functionWe don’t need to set name for function each time.
Lambda + Closures• Lambda – anonymous function with
short syntax.
• Closure - the function captures variables from the scope.
Problem
Solving- Iterators & foreach loop
Iterator pattern
IEnumerable<T>• IEnumerable<T> requires only one
method to be implemented – IEnumerator<T> GetEnumerator()
• Do not modify collection in the iteration process.
• Remember that IEnumerables are lazy
IEnumerator<T>• Current returns the same object until
MoveNext is called. MoveNext sets Current to the next element.
• Initially, the enumerator is positioned before the first element in the collection.
• If MoveNext() == false – Current is undefined.
• You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.
http://msdn.microsoft.com/ru-ru/library/s793z9y2(v=vs.110).aspx
Usage
Foreach loop• The foreach statement repeats a
group of embedded statements for each element in an array or an object collection that implements the IEnumerable<T>
Yield• Method should returns
IEnumerable<T>• Yield return one value and do
MoveNext() = true• Yield break do MoveNext() = false
LINQ• LINQ - Language-Integrated Query
• Extensions methods was implemented for LINQ
What we can to do with linq?
- Filter/Transform/Aggregate/Generate data
LINQ and LINQ extensions
RecursionRecursion – see recursion
Why we need it?- Tree traversing- Working with Linked Lists- etc…
Sum up• Use LINQ and LINQ extension methods – to declaratively specify what you want – to simplify your code– to generalize your code– to create complex abstractions from
simple ones• Remember that IEnumerables are lazy• Use delegates to separate
implementation and interface