Jump to content
  • Advertisement
Sign in to follow this  

[.net] convert delegate?

This topic is 4406 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hum, I find it very strange that I can't do the following with delegates in c#:
delegate void D1();
delegate void D2();

public static void test() {}

D1 d1 = test;
D2 d2 = d1;  //can't convert from D1 to D2
I find it very irritating to have to do like this in many situations:
delegate Function1P<P1>(P1 p1);
delegate Function2P<P1, P2>(P1 p1, P2 p2);
/* etc... */
When In many cases I would like to have a more readable name:
delegate MyCoolFunction<IdT>(IdT id);
But to make the MyCoolFunction delegate usable across my library, so It can be used in different stand alone plugins, I would have to use the Function1P everywhere I want such a delegate... Or is there a way around this?

Share this post

Link to post
Share on other sites
In C#/.Net, as you've found out, delegates are strongly typed, even by name. So D1 and D2 are treated as separate types. That is a deliberate language feature. If you could assign a D1 instance to a D2 instance, then things become a royal pain when you change the type of D1 (add a parameter for example) - you have a bit of mess to sort out. By preventing that sort of assignment, changing D1 will again cause compiler errors wherever D1 is used, but it is much easier to sort out. Best practice is to have a unique delegate for each instance where delegates are used.


Share this post

Link to post
Share on other sites
I guess so, though I did find a way to convert the delegates - unfortunately it's not type safe on compiletime, so you have to be careful using it.

public static class FunctionUtil
public static T CastTo<T>(this Delegate source)
where T : class
if (source == null)
return null;

Delegate[] delegates = source.GetInvocationList();
if (delegates.Length == 1)
return Delegate.CreateDelegate(typeof(T), delegates[0].Target, delegates[0].Method) as T;

for (int i = 0; i < delegates.Length; i++)
delegates = Delegate.CreateDelegate(typeof(T), delegates.Target, delegates.Method);

return Delegate.Combine(delegates) as T;

This converts a delegate to your specified delegate type T. In some cases where you know they are of same type, it's ok. Though be aware of performance issues in certain contexts.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!