Generic methods save typing

I just played around with generic methods in C#. They saved my typing a lot code. I have lists of different types. First, I had a static CreateArray-method on every class. With the method below, these have been refactored away.

In the code below, note the part where T:new(). This is a constaint on the type T, making sure the type has a constructor without parameters.

public static T[] CreateArrayOf<T>(uint length) where T:new()
{
    T[] result = new T[length];
    for (int i = 0; i < length; i++) result[i] = new T();      
    return result;
}
 
blog\generic_methods.txt · Last modified: 2008-08-08T08:34
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki