views:

169

answers:

5
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();
   }
}
+3  A: 

Don't use as, just cast:

((ILol)this).LOL();
Mark Byers
+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
Come again? What's wrong with the `as` cast, versus the non-`as`?
bobobobo
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
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
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
+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
You realize your code example implement it explicitly still, right? :)
Isak Savo
Good lord, that's embarrassing. Fixed - thank you!!
ladenedge
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
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
A: 

You don't need to cast at all. Since ROFL implements ILOL you can simply call this.LOL() or even just LOL();

MrGumbe
-1 Wrong. ROFL explicitly implements `ILOL` and cannot access `ILOL` members without having access to an instance (`this` casted) of `ILOL`.
statenjason