I’m trying to learn about generics, and I’m trying to make my own generic list class.
The thing is that I don’t know how to get around default(T);
public IEnumerator<T> GetEnumerator()
{
T current = data[forIndex];
while (!current.Equals(default(T)))
{
yield return current;
forIndex++;
current = data[forIndex];
}
forIndex = 0;
}
This construction means that it will stop iterating through my list if it contains the value 0, since default(T) is 0. Can anyone tell me how to get around this?
I think your mistake is that you rely on the fact that the internal array only has default values at the end, not in the valid data range. This assumption can be false for any element type (0 for ints, null for ref types. You can store nulls in a
List<string>for example).So you can’t use this technique.
Instead, I recommend that you keep the current count of items in an integer field. That way you can implement your iterator correctly. Like this:
(Some code taken from another answer).
Now, if you insist to do it your way, you can do this:
This works even if current is of type T and T is unconstrained. If T is a value type the condition is always true (because a value type would be boxed first and any boxed value is != null).