1

I need to do something like the following but getting the above error

class PrioritizedEvent<DelegateType>
{
    private ArrayList delegates;

    public PrioritizedEvent()
    {
        this.delegates = new ArrayList();
    }

    public void AddDelegate(DelegateType d, int priority)
    {
        this.delegates.Add(new PrioritizedDelegate<DelegateType>((Delegate)d,    priority));
        this.delegates.Sort();
    }

    protected class PrioritizedDelegate<DelegateType> : IComparable
    {
        public Delegate d;
        public int priority;

        public PrioritizedDelegate(Delegate d, int priority)
        {
            this.d = d;
            this.priority = priority;
        }
    }
}

I cannot caste the DelegateType D to Delegate

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
user2224555
  • 15
  • 1
  • 5

2 Answers2

1

Indeed, you cannot specify a : Delegate constraint - it simply cannot be done (the compiler stops you). You might find it useful to add a where DelegateType : class, just to stop usage with int etc, but you can't do this all through generics. You will need to cast via object instead:

(Delegate)(object)d

However, personally I think you should be storing DelegateType, not Delegate, i.e.

protected class PrioritizedDelegate : IComparable
{
    public DelegateType d;
    public int priority;

    public PrioritizedDelegate(DelegateType d, int priority)
    {
        this.d = d;
        this.priority = priority;
    }
}

Note I removed the <DelegateType> from the above: because it is nested inside a generic type (PrioritizedEvent<DelegateType>) it already inherits this from the parent.

For example:

class PrioritizedEvent<TDelegateType> where TDelegateType : class
{
    private readonly List<PrioritizedDelegate> delegates
        = new List<PrioritizedDelegate>();

    public void AddDelegate(TDelegateType callback, int priority)
    {
        delegates.Add(new PrioritizedDelegate(callback, priority));
        delegates.Sort((x,y) => x.Priority.CompareTo(y.Priority));
    }

    protected class PrioritizedDelegate
    {
        public TDelegateType Callback {get;private set;}
        public int Priority {get;private set;}

        public PrioritizedDelegate(TDelegateType callback, int priority)
        {
            Callback = callback;
            Priority = priority;
        }
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Your DelegateType is completely unrestricted. For all the compiler knows it could be an int or some class or a delegate.

Now normally you could use some constraints to restrict the generic type, unfortunately restricting it to a delagate is not allowed.

Marc Gravell's answer to the question why C# Generics won't allow Delegate Type Constraints gives you a workaround.

Community
  • 1
  • 1
Dirk
  • 10,668
  • 2
  • 35
  • 49