-
Notifications
You must be signed in to change notification settings - Fork 1
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 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.
-
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>
Dictionary<TKey, TValue>
LinkedList<T>
List<T>
Queue<T>
SortedDictionary<TKey, TValue>
SortedSet<T>
Stack<T>
This contains a couple of important collection objects that notify listeners when the collection is modified.
ObservableCollection<T>
ReadOnlyObservableCollection<T>
- Abstract Classes
- Access Modifiers
- Anonymous Methods
- Anonymous Types
- Arrays
- Attributes
- Console I/O
- Constructors
- Const Fields
- Delegates
- Enums
- Exceptions
- Extension Methods
- File IO
- Generics
- Interfaces
- Iterators
- LINQ
- Main
- Null Operators
- Parameters
- Polymorphism
- Virtual Functions
- Reflection
- Serialization
- Strings
- Value Types
- "Base" Keyword
- "Is" and "As"
- "Sealed" Keyword
- nameof expression