I won't be discussing anything about Explicit interface implementation feature in C# here. I am sure either you know about it or there are many great articles on the web that you can take a look at.
But I must say that you must read the excellent article by my friend Abhiseksur on the internals of Explicit interface implementation feature in C#.
Let me outline a particular point from Abhisek’s article which I or this article is interested in:
- Explicit method is always implicitly
private
to its type - You can’t modify/specify any modifier to Explicit method
So that means we can't do this as shown below:
1. interface IMyInterface
2. {
3. void InterfaceMethod();
4. }
5.
6. class MyClass : IMyInterface
7. {
8. void IMyInterface.InterfaceMethod()
9. {
10.
11. }
12. }
13.
14. new MyClass().InterfaceMethod()
So now, any developer can be relaxed about this explicit implementation method that his code is fail proof since it's private
and nobody can corrupt it. Yes, logically at least, it looks like that. But my curiousness doesn’t end here. Now let's see how safe this Explicit implementation method in this class is.
Assume the below code:
1. abstract class MyAbstractClass
2. {
3. public int MyValue { get; set; }
4. }
5.
6. interface IMyInterface
7. {
8. void InterfaceMethod(MyAbstractClass absClassObj);
9. }
10.
11. class MyClass : IMyInterface
12. {
13. void IMyInterface.InterfaceMethod(MyAbstractClass absClassObj)
14. {
15. var value = absClassObj.MyValue;
16. }
17.
18. public void SomeOtherMethod()
19. {
20.
21. }
22. }
23.
24. class SomeEvilClass
25. {
26. MyClass myclass = new MyClass();
27.
28. public void SomeEvilMethod()
29. {
30. (myclass as IMyInterface).InterfaceMethod(null);
31. }
32. }
This above code crashes the application. Although it’s not a great catch what I am speculating here, but could be a bit of a flaw if the developer fails to oversee it. I have no idea where and when we make use of this feature. But the workaround I am thinking of is to keep the interface internal, at least you are sure that your assembly code is not evil and you can control it somehow but on the flip side, it won't pay off much if I have an interface which is not public
.
That’s all friends, please leave comments for my learning.
Thanks for reading.
Zen