tags:

views:

66

answers:

3
public class StuffDoer<T>
{
    // do stuff
}

I want that this is always of type string, so instead of doing this:

StuffDoer<string> stuffer = new StuffDoer<string>();

I want to be able to do this:

StuffDoer stuffer = new StuffDoer();

and if I need a StuffDoer of type int, just define that with generics.

StuffDoer<int> stuffer = new StuffDoer<int>();

Is this possible?

+3  A: 

You can just setup a plain StuffDoer class that inherits from StuffDoer<T>:

public class StuffDoer : StuffDoer<string>
{
    // ...
}

public class StuffDoer<T>
{
    // ...
}
LukeH
I think mine is a lot more attractive!
Chris S
+3  A: 
public class StuffDoer<T>
{
    // do stuff
}

public class StuffDoer : StuffDoer<string>
{
    // do stuff
}
Chris S
+2  A: 

Rather than using subclasses where there's no real specialization going on, I would suggest using a separate static "factory" class:

public static class StuffDoer
{
    public static StuffDoer<string> Create()
    {
        return new StuffDoer<string>();
    }

    public static StuffDoer<T> Create<T>()
    {
        return new StuffDoer<T>();
    }


    public static StuffDoer<T> Create<T>(T item)
    {
        StuffDoer<T> ret = new StuffDoer<T>();
        ret.Add(item); // Or whatever
        return ret;
    }
}

The last method lets you use type inference as well:

StuffDoer<int> doer = StuffDoer.Create(10);

This doesn't let you write new StuffDoer() admittedly - but I think it's a cleaner solution. Creating a non-generic derived class just as a sort of "type alias" feels like an abuse of inheritance to me.

Jon Skeet
the approach of inheritance indeed looks good, but this might indeed be better because it is more intended to hide instead of real inheritance
Natrium