Conrad Clark
Conrad Clark

Reputation: 4526

What happens in a static parametrized class regarding its instance?

Suppose I have this class:

public class DispatcherService<T>
{
    private static Action<T> Dispatcher;

    public static void SetDispatcher(Action<T> action)
    {
        Dispatcher = action;
    }

    public static void Dispatch(T obj)
    {
        Dispatcher.Invoke(obj);
    }
}

Let me get this straight... I'll have only one instance of DispatcherService<T> for each type, and only when I call it. Right?

Just asking for memory issues.

Upvotes: 0

Views: 125

Answers (2)

Aliostad
Aliostad

Reputation: 81660

I'll have only one instance of DispatcherService for each type

Yes.

and only when I call it. Right?

Yes.

The code is emitted by CLR when it needs to use it.


Note

if I where you I would change it to singleton.

public class DispatcherService<T>
{

    private static readonly DispatcherService<T> _dispatcher = new DispatcherService<T>();
    private Action<T> _action;

    private DispatcherService() {}

    public static DispatcherService<T> Dispatcher
    {
        get {return _dispatcher ;}
    }

    public void SetDispatcher(Action<T> action)
    {
        Dispatcher = action;
    }

    public void Dispatch(T obj)
    {
        Dispatcher.Invoke(obj);
    }
}

Upvotes: 2

Jon
Jon

Reputation: 437444

You can have as many instances of DispatcherService as you like, since the class can be instantiated freely. It's another matter that there's no point to that because it has no instance methods. You can change it to public static class DispatcherService<T> if it's not meant to be instantiated, as in this example.

You will also have at most one instance of DispatcherService.Dispatcher for each type, which is what you probably want to know. If you don't access DispatcherService for a specific T, no resources will be allocated for that T.

Upvotes: 1

Related Questions