user2877820
user2877820

Reputation: 307

How can I use the same generic type in multiple methods in a non-generic static class

I am trying to create a static (thus non-generic) class which contains a method called

Initialize<T>();

This method will be called on startup and will define the generic type of the class. So I want to be able to set the return value of other methods to the same type as T.

The result should look like something like this:

public static class ServiceClientBase
{
    private static IRestClient _client;

    public static void Initialize<T>(T restClient)
    {
        _client = restClient;
    }

    public static T GetClient()
    {
        return (T)_client;
    }
}

Obviously this doesnt work because GetClient() doesnt know type T. But T from GetClient should be equal to T from Initialize.

Is there a way to accomplish this? If not, is there a useful pattern, to accomplish something similar?

Thanks alot!

Upvotes: 0

Views: 69

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500335

I think you've made an incorrect assumption here:

I am trying to create a static (thus non-generic) class

Static classes can absolutely be generic. I believe you just want:

public static class ServiceClientBase<T> where T : IRestClient
{
    private static T _client;

    public static void Initialize(T restClient)
    {
        _client = restClient;
    }

    public static T GetClient()
    {
        return _client;
    }
}

Then you'd use:

ServiceClientBase<Foo>.Initialize(client);
...
Foo foo = ServiceClientBase<Foo>.GetClient();

Your non-generic version would cause problems if you called Initialize twice with two different types - you've only got a single field. With the generic type, you've got a field per constructed type.

As a side-note, ServiceClientBase is a very odd name for a static class - it sounds like it should be the base class for something, but nothing can derive from a static class.

Secondly, this is just a glorified singleton pattern. I'd encourage you to investigate dependency injection instead as a better way of handling this sort of thing.

Upvotes: 3

Related Questions