Essential C# Interfaces  Suggest an edit

Hiding members with Explicit Implementation

Don’t you hate it when interfaces pollute you class with too many members you don’t even care about? Well I got a solution! Explicit Implementations

public interface IMessageService {
    void OnMessageRecieve();
    void SendMessage();
    string Result { get; set; }
    int Encoding { get; set; }
    // yadda yadda
}

Normally you’d implement the class like this.

public class MyObjectWithMessages : IMessageService {
     public void OnMessageRecieve(){

     }

     public void SendMessage(){

     }

     public string Result { get; set; }
     public int Encoding { get; set; }
}

Every member is public.

var obj = new MyObjectWithMessages();

// why would i want to call this function?
obj.OnMessageRecieve();

Answer: I don’t. So neither should it be declared public but simply declaring the members as private will make the compiler throw an error

The solution is to use explicit implementation:

public class MyObjectWithMessages : IMessageService{
    void IMessageService.OnMessageRecieve() {
        
    }

    void IMessageService.SendMessage() {
        
    }

    string IMessageService.Result { get; set; }
    int IMessageService.Encoding { get; set; }
}

So now you have implemented the members as required and they wont expose any members in as public.

var obj = new MyObjectWithMessages();

/* error member does not exist on type MyObjectWithMessages. 
 * We've succesfully made it "private" */
obj.OnMessageRecieve();

If you seriously still want to access the member even though is explicitly implement all you have to do is cast the object to the interface and you good to go.

((IMessageService)obj).OnMessageRecieve();

Table Of Contents
22 Enum
25 GUID
41 Interfaces
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close