Events and Delegates [Answered]
I'm encountering a very strange error. I have a delegate and an event inside my
IAuthService
. Now when other class are trying to inherit from the interface. For some reason I have to implement the event explicitly?
The first one is working fine!
But the second one is complaining for some reason.16 Replies
Btw, put that delegate definition out of there
It's not a class member, but kind of a type definition on its own
I mean, it can be
Can you show the definition of
IAuthService
?It's not bound to an interface contract + every single implementing type would theoretically define the same delegate
looks like this
Yep, ok
So, here's what's happening
Your
AccountCreated
in AuthService
has a return type of AuthService.AccountCreatedEventHandler
What it actually needs to be is IAuthService.AccountCreatedEventHandler
Yes
But I don't get it
Just straight up remove the
AccountCreatedEventHandler
delegate in AuthService
AuthService.AccountCreatedEventHandler
!= IAuthService.AccountCreatedEventHandler
Those are completely separate typesWhen declaring a delegate, youre declaring it as if it was a class
You declare it once, and now you can use that delegate
It's not a per-class member
Yes it seems like I don't need to even have the delegate inside the
AuthService
. But I would be lying if I said I understood the event thing. AuthService.AccountCreatedEventHandler != IAuthService.AccountCreatedEventHandler
I get that they don't have the same types. But for the other part it's still a bit confusing.The other part?
I mean normally when I implement a method from an Interface. It doesn't force me to Implement it explicitly? This is the part which is confusing to me. Maybe I have misunderstood the entire concept.
You're not implementing explicitly
You're saying "The return type is the
AccountCreatedEventHandler
defined in IAuthService
"You defined the same delegate twice, now in the deriving implementing class you mentioned the delegate name
And thus it prioritized the one from right below it, though the interface means the one from the interface
That's why you had to explicitly mention "the one from the interface"
For explicit implementation, the
Interface.
goes on the method/property name, not on a type
Explicit implementation would have looked like this:
Oh shit I get it know. Stupid me. Thank you very much guys.
✅ This post has been marked as answered!