C# Generics abused

This is my first post and as a tradition in picking up any new computer language, one would start off with a “Hello, World” program but I am going to discuss about how one of the great features of C# language, Generics can be abused.

Here’s the definition of Generics from MSDN.

Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities.

Let’s assume that I am trying to build a managed library for some unmanaged code. Basically wrap the unmanaged code by .net.

I have with me a set of C functions which do the same operation on different data types.

void PerformActionUInt(uint[] data);

void PerformActionByte(byte[] data);

void PerformActionUShort(short[] data);

We might think making use of a generic method, which can drastically reduce the method overload bloat.
Here’s how the .net generic method wraps the above C functions. This generic method contains logic to figure out which C function to be invoked based on the data passed.


private void PerformAction(T[] data)
{
    uint[] uintData = data as uint[];
    if (uintData != null)
    {
        PerformActionUInt(uintData);
        return;
    }

    ushort[] ushortData = data as ushort[];
    if (ushortData != null)
    {
        PerformActionUShort(ushortData);
        return;
    }

    byte[] byteData = data as byte[];
    if (byteData != null)
    {
        PerformActionByte(byteData);
        return;
    }

    throw new ArgumentException(data.GetType() + " not supported");
}

This, according to me, is a clear abuse in the usage of generics. And following are the problems with the above design:

1. Performance cost : Casting is performed on the passed data against each supported data type to figure out the data type.

2. Potential runtime exception: What if the method is passed with an unsupported data type? Yes, one can argue that documentation would be updated on the supported data types, but how many of us would read the documentation until we run into any problem?

I would prefer to have overloads for the above methods, and not use generics, which is not meant for this particular case.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s