Click here to Skip to main content
15,794,475 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I' having tough time with handling generics in C#, following is the code snippet that i'm using

public delegate void SyncEventDelegate<TEntity>(TEntity entity, SyncInfo requestInfo);

i need to add this delegate to a Dictionary

private Dictionary<Type, SyncEventDelegate<ISynchronizeableEntity>> _delegateCollection;

the method that passes the the delegate to register has the following signature.

public void Register<TEntity>( SyncEventDelegate<ISynchronizeableEntity> syncEventDelegate) where TEntity : ISynchronizeableEntity

it's working fine for the moment , but I have a doubt if i change the register method signature to the following format , i get a compiler error.

public void Register<TEntity>( SyncEventDelegate<TEntity> syncEventDelegate) where TEntity : ISynchronizeableEntity

I thought it should work since TEntity is derived from ISynchronizeableEntity, but it doesn't.

I really appreciate if someone can explain this.
thanks in advance.

1 solution

Where exactly do you get the error?
I created a delegate and a method register with the signature you say that causes the error, and it works.

I think your problem is that you want a Register that receives a SyncEventDelegate<TEntity> and tries to register it in a dictionary that is still of type SyncEventDelegate<ISynchronizeableEntity>

In this case, is like you want to put an Action of string inside an Action of object. There is no valid variance for that, as if you receive the Action of object you can pass any object as parameter, when only strings should be valid parameters.
I think you should also change the type of the dictionary or, if that's not possible, you will need to always receive the parameter as an action of the interface. If needed, the method called by the delegate should do a cast.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900