Thursday, April 02, 2009

Did you know? Interface members are allowed to be private

This one comes as a surprise to most people, but it is possible to have a private implementation for an interface member, let's look at a very simple example, just for purposes of the ilustration.

public interface ITest {

void Test();

}

public class Test : ITest {

void ITest.Test() {

Console.WriteLine("test");

}

public void Test2() {

Console.WriteLine("test2");

}

}

class Program {

static void Main(string[] args) {

ITest t = new Test();

t.Test();

Test t2 = new Test();

//t2.Test(); //<<=== doesn't compile


If you don't believe it you can try it of course.

But why is this useful or how do you use this?

The technique allows you to ensure that the method is only visible to those who are using a variable of the interface type. All this does is to force the use of the member through an instance of the interface, meaning, for this example, if you want to get access to the .Test method, you can only do so through a variable of type ITest.

The only trick to make this work is to precede the member declaration with the Interface type as in:

void ITest.Test();

Not the most useful of tricks, but something to have on the bag of tricks, or maybe something to make you win a bet ;)

No comments: