C# Empty Enumerator

11 Comments »

This article provides C# code for an empty enumerator.  This generic class can be used to simulate enumeration over an empty collection of any type of objects.  Here is the code:

Read the rest of this entry »

Generic Class: Duplicate Method Overloads

4 Comments »

When two overloads of a method in a generic class are the same (have identical type arguments) as a result of the generic type you specified, which method is called?

Read the rest of this entry »

Nested Generics

3 Comments »

Given two generic classes:

public class Type1<T> {}
public class Type2<T> {}

.NET allows you to specify a generic type as the type of another generic type:

Type1<Type2<int>> obj = new Type1<Type2<int>>();

Read the rest of this entry »

Reverse an Array

7 Comments »

It’s easy to reverse the contents of an array using C# generics:

Read the rest of this entry »

Convert Generic ICollection

4 Comments »

As discussed in a previous article, Generics provides the ability to create strongly-typed collections in C#. Unfortunately, C# currently does not support generics variance, which would allow inheritance of generic types.

Read the rest of this entry »

Convert Between Generic IEnumerable

4 Comments »

Generics in .NET 2.0 provides the ability to create strongly-typed collections in C#. Unfortunately, C# currently does not support generics variance, which would allow inheritance of generic types.

For example, consider a list of strings and a list of objects:

List<string> strings = new List<string>();
strings.Add( "hello" );
strings.Add( "goodbye" );
List<object> objects = new List<object>();
objects.AddRange( strings );

The final line in the code above generates a compiler error. But why? Since the ‘string’ class derives from the ‘object’ class, one would expect List<string> to also implicitly derive from List<object>. This capability is called generics variance, but C# currently does not support it.

Fortunately, you can brute force your way to a solution by creating a generic ConvertIEnumerable method:

Read the rest of this entry »