Website Links

Tuesday, 6 December 2016

C# Generics


  • Used to not be generics and this gave you one of two options:
    • Use object as the type everywhere, but this had a performance penalty in that casting would have to be performed to get the actual object type
    • Duplicate code for different types
  • Most developers will be mmore frequently using generics as opposed to creating them, but if you wanted to create a generic class you would use public class Generic<T>
  • The generic collections are one of the commonly used inbuilt generics
  • Can restrict generic type e.g. public T Max<T>(T a, T b) where T : IComparable, so that only IComparable objects can be used in the generic method
  • Can have generic methods in non generic classes, just need to specify the generic at method level if it's not specified at class level
  • Generic constraint types:
    • where T : IComparable; T implements the IComparable interface
    • where T : Product; T is of type Product or any of its children
    • where T : struct; T is a value type, a use case for this is a nullable int implementation
    • where T : class; T is a reference type
    • where T : new(); T has a default constructor, a use case for this is when you want to instantiate a generic object
  • Can chain constraints e.g. where T : IComparable, new()

References

C# Generics