- Home /
Can you subscribe a delegate to an event?
If I assign a local method to a delegate, I can't subscribe it to the event. Is this not possible?
Answer by Bunny83 · Sep 04, 2021 at 09:36 AM
Well, it's not clear how your EAfterAttacking event is defined. However it most likely has it's own delegate type. You can not just assign different delegate types to each other. However you should be able to create a new instance of the delegate type you want to subscribe to and pass your delegate as parameter to the constructor. Since we don't know the delegate type of your event we can't really show you any code. Though for reference, see this SO question.
Please do not post code samples as an image. Concent in images can not be searched and we can't copy anything from it (besides manually retyping everything) which makes it quite difficult to provide a proper answer. Just post the code as text, select all the code text and press the 101 / 010 button to mark it as a code block.
// just like that
Answer by jondigarcia · Sep 05, 2021 at 12:31 AM
Hi @Bunny83 , thanks for the answer! Below is the code I'm working with - apologies for me being a noob here, I can't seem to paste the text properly. Appreciate any additional inputs you may have:
public delegate void HeroesEvent(IHero thisHero, IHero targetHero);
public event HeroesEvent EBeforeAttacking;
private delegate void TestMethods(IHero thisHero, IHero targetHero);
private TestMethods _testMethods;
private void SubscribeTest(IHero thisHero, IHero targetHero)
{
//If direct subscribe, there is NO error
EBeforeAttacking += SomeLocalMethod;
//If I try to assign the mehtod to a delegate with the same signature, I can't subscribe the delegate
_testMethods = SomeLocalMethod;
EBeforeAttacking += _testMethods;
}
private void SomeLocalMethod(IHero thisHero, IHero targetHero)
{
}
@Bunny83 I already figured it out based on your answer and the reference you've provided. I should've used "HeroesEvent" and not created a new delegate type to assign the local method to.
Thanks for the help!