Search code examples
c#.netgenericstype-parameterstatic-classes

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.


Solution

  • 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);
        }
    }