0
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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

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

public class StuffDoer<T>
{
    // ...
}

1 Comment

I think mine is a lot more attractive!
3
public class StuffDoer<T>
{
    // do stuff
}

public class StuffDoer : StuffDoer<string>
{
    // do stuff
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.