Skip to content

Generics

Mario Gutierrez edited this page Jan 7, 2017 · 2 revisions

Generics provide better performance because they prevent boxing or unboxing penalties when storing ValueTypes.

// Generic method.
void AddToList<T>(T item)
{
  Console.Log("Adding item of type " + typeof(T));
}

// Generic struct.
public struct Point<T>
{
  public void ResetPoint()
  {
    x = default(T); // Sets the default value w.r.t. the generic type.
    y = default(T);
  }
}

Generic Constraints

Generic class using constraints on the generic type.

public class MyGenericClass<T> where T : class, IDrawable, new()
{
 // ...
}

Possible Constraints:

  • struct - ValueTypes
  • class - ReferenceTypes
  • new() - Must have a default ctor. Must be last in the list.
  • MyCustomType
  • IMyInterface - Can have multiple interface constraints.
  • U - Depends on generic type 'U' (generic param. U must also specified). Does not have to be letter 'U' of course.
class MyGeneric<T, U>
  where T : Set<U>, ISomeInterface
  where U : struct
  { }

Notice the where TypeParam : [constraints] sections are not separated by commas.

The System.Collection.Generics Namespace

Generic Interfaces

  • ICollection<T> - Defines general characteristics (e.g., size, enumeration, and thread saftey) for all generic collection types.
  • IComparer<T>
  • IDictionary<T> - Allows a generic collection object to represent its contents using key-value pairs.
  • IEnumerable<T>
  • IEnumerator<T>
  • IList<T>
  • ISet<T>

Generic Collections

  • Dictionary<TKey, TValue>
  • LinkedList<T>
  • List<T>
  • Queue<T>
  • SortedDictionary<TKey, TValue>
  • SortedSet<T>
  • Stack<T>

The System.Collections.ObjectModel Namespace

This contains a couple of important collection objects that notify listeners when the collection is modified.

  • ObservableCollection<T>
  • ReadOnlyObservableCollection<T>
Clone this wiki locally