interface ILol
{
void LOL();
}
class Rofl : ILol
{
void ILol.LOL()
{
GlobalLOLHandler.RaiseROFLCOPTER(this);
}
public Rofl()
{
//Is there shorter way of writing this or i is there "other" problem with implementation??
(this as ILol).LOL();
}
}
views:
169answers:
5
+7
A:
You may want to change the cast from (this as ILol)
to ((ILol)this)
. An as cast is allowed to return null, which could cause confusing errors later and which the compiler has to test for.
Stewart
2010-05-10 20:01:10
Come again? What's wrong with the `as` cast, versus the non-`as`?
bobobobo
2010-05-10 20:15:23
Using the object returned from `as` before checking for null is a bad practice. The code above won't exhibit any problems as written, but won't be as resilient during refactoring.
ladenedge
2010-05-10 20:28:39
The as cast can return null, so the compiler needs to test for null before calling the method so it can generate the null reference exception. a regular cast can't ever return null so the compiler can elide the test for null.
Stewart
2010-05-11 12:39:02
A:
No not if you are explicitly implementing the interface. If you make it implicit by removing the interface name from the implemented method it'll work as you want.
void LOL()
{
GlobalLOLHandler.RaiseROFLCOPTER(this);
}
public Rofl()
{
LOL();
}
Isak Savo
2010-05-10 20:02:10
+5
A:
You've implemented the interface explicitly which, in general, you don't need to do. Instead, just implement it implicitly and call it as you would any other method:
class Rofl : ILol
{
public void LOL() { ... }
public Rofl()
{
LOL();
}
}
(Note your implementation will also need to be public.)
ladenedge
2010-05-10 20:02:36
You realize your code example implement it explicitly still, right? :)
Isak Savo
2010-05-10 20:08:14
What is difference between implicit and explicit implementation? If i dont add ILol. before LOL, then compiler complains that there is no implimentation of ILol.LOL.
0xDEAD BEEF
2010-05-11 07:07:00
Explicit interfaces can only be called when the object is cast to the interface type. There are various obscure advantages to this, but otherwise you should avoid it. As for why your code isn't working, I can only guess: are the methods that implement your interface publicly accessible?
ladenedge
2010-05-11 13:32:46
A:
You don't need to cast at all. Since ROFL
implements ILOL
you can simply call this.LOL()
or even just LOL();
MrGumbe
2010-05-10 20:04:45
-1 Wrong. ROFL explicitly implements `ILOL` and cannot access `ILOL` members without having access to an instance (`this` casted) of `ILOL`.
statenjason
2010-05-10 20:13:48