Reputation: 2104
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();
}
}
Upvotes: 4
Views: 29292
Reputation: 103
using System;
public class Entry{
public static void Main(){
MyClass m = new MyClass();
m.DoWork();
}
}
interface IDemo1{
void DoWork();
}
interface IDemo2{
void DoWork();
}
public class MyClass : IDemo1, IDemo2{
public void DoWork(){
Console.WriteLine("Class Do work");
if(true){ // as per any condition
((IDemo1)this).DoWork();
}else{
((IDemo2)this).DoWork();
}
}
void IDemo1.DoWork(){
Console.WriteLine("Demo 1 Do work");
}
void IDemo2.DoWork(){
Console.WriteLine("Demo 2 Do work");
}
}
Upvotes: 1
Reputation: 13419
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.)
Upvotes: 10
Reputation: 35884
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();
}
Upvotes: 0
Reputation: 983
You don't need to cast at all. Since ROFL
implements ILOL
you can simply call this.LOL()
or even just LOL();
Upvotes: -3
Reputation: 4028
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.
Upvotes: 9