Skip to content

Day 01 Generics and Extension Methods

Kobi Hari edited this page Oct 13, 2020 · 3 revisions

Day 01 - Generics, Extension Methods

Projects:

Fun With Generics Touching the hard points of .net Generics: Constraints, Covariance and Inference

Generics

  • The purpose of Generics
  • About Boxing and Unboxing
  • Static members of Generic classes
  • Generic Constraints
    • How to create base class constraint
    • How to create interface constraint
    • How to create value type / reference type constraint
    • How to create default constructor constraint
  • Generic Inference
  • Generic Invariance, Covariance and Contravariance

Equatable and Comparable

  • We have created a value type for complex numbers: Complex
  • We have implemented the IComparable<Complex> and IComparer<Complex> interfaces to allow a "natural" and "alternative" orders
  • We have implemeneted IEquatable<Complex> to allow it to compare itself to other Complex instances
  • We discussed the Equals that we derive from object and how to override it
    • Always override the Equals method from object (the compiler warns if you do not)
    • Always override the GetHashCode method too (the compiler warns if you do not) - this is important to allow the object to be used as key in HashSets

Collections in .NET

  • We have discussed the various types of collections that we have in .net and what they are specifically good for
    • List<T> - Ordered collection that allows Fast random access by index (O(1)), avarage modification (o(1), O(N)), and slow find operations (O(N))
    • Dictionary<K, T> - Store items by keys instead of indices. random access by key: O(1) (or very close to, depends on hashing algorithm) Add and remove like List. Find operations are O(1) by key and O(N) by value
    • HashSet<T> - Very fast access, modifications, and find, but do not support order (no notion of index).
    • We have also discussed SortedSet, SortedList, SortedDictionary, Stack and Queue briefly

Extension Methods

  • We created a static class and a static method inside it
  • We have seen how to add a new invokation syntax by adding the keyword this to the first parameter of the method
  • By using extension methods, we saw that we can create Fluent APIs which are much more readable