C# 02 - Generics
C# 02 - Generics
2
Generics
Ateik Alzehla
Content
This what will happen with other types like: float, double or decimal.
So, we are going to create a method for every type. THIS IS A PROBLEM.
An overview of generics (Continued)
We can solve this problem with object type:
public object Add(object x, object y)
{
return x + y;
}
But this is not Type Safe, especially with complex type like classes, and it
doesn’t allow us using the feature of the type such as methods properties
If there’s a special requirement for a generic type, use descriptive names
for the type names.
public class Dictionary<TKey,TValue>{ }
public class Dictionary<TK,TV>{ }
public delegate void EventHandler<TEventArgs>()
Creating generic classes
public class MyList public object this[int i]
{ {
private object[] _items; get
public MyList():this(0) {
{ return _items[i];
}
} set
public MyList(int capacity) {
{ _items[i] = value;
_items = new object[capacity]; }
} }
public void Add(object item) public int Count { get=> _items.Length; }
{ public IEnumerator GetEnumerator()
object[] temp = new object[Count + 1]; {
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
temp[i] = this[i]; yield return _items[i];
} }
temp[Count] = item; }
_items = temp;
}
Creating generic classes (Continued)
public class MyList<T> public T this[int i]
{ {
private T[] _items; get
public MyList() : this(0) {
{ return _items[i];
}
} set
public MyList(int capacity) {
{ _items[i] = value;
_items = new T[capacity]; }
} }
public void Add(T item) public int Count { get => _items.Length; }
{ public IEnumerator<T> GetEnumerator()
T[] temp = new T[Count + 1]; {
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
temp[i] = this[i]; yield return _items[i];
} }
temp[Count] = item; }
_items = temp; }
}
Generics Features:
Default values
Uses keyword: default
Is used to initialize generic types either to null or to 0
Constraints
If the generic class needs to invoke some methods from the generic type, you have to add
constraints.(class, struct, IFoo, Foo, new(), T2)
Inheritance
Same inheritance.
Partial specialization.
Static members
Static class for every type;
Generic Interfaces & Generic structs:
Same as Classes but with much more.
each type parameter of a generic interface can be marked covariant ( out ),
contravariant ( in ), or invariant (no annotation)
Invariant => same as class
Covariant: method return type;
Contravariant: method arguments type
Generic structs: same as Classes but without inheritance features
Nullable<T>
Generic methods:
Methods can be generic.
With a generic method, the generic type is defined with the method
declaration.
Can be defined within non-generic classes.
Generic constraints can be used.
Useful for Extensions.
Any questions?