Click here to Skip to main content
13,291,503 members (60,195 online)
Rate this:
Please Sign up or sign in to vote.
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.
Posted 3-Nov-12 4:13am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.171207.1 | Last Updated 3 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100