Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the VS Metadata view does not display explicit interface implemented members

The other day i was looking at C# Boolean struct metadata.

Boolean implements the interface IConvertible. But looking at Boolean's members i could not see most of the IConvertible members.

I've done some tests with some colleagues, including creating our own classes, and came to the conclusion that IConvertible must be implemented explicitly for Boolean.

The question is, why are they not visible? I understand it might be a 'by design decision' but i understand that it would add greater value if they were visible to anyone inspecting the metadata.

The tests were done in VS2010 .NET4.0

like image 623
Luis Filipe Avatar asked Sep 01 '11 09:09

Luis Filipe


2 Answers

The reason is that those methods are there just to implement the I-interface and not to augment the class' public interface.

What I mean is that if you have the following:

public class MyClass : IConvertible
{
 // implementation
}

You might want MyClass to be convertible, indeed, so you can pass references of it to methods that expect IConvertible:

public void DoSomethingWithConvertible(IConvertible conv)

But you might not want variables of type MyClass to expose the Convert methods. You simply don't want MyClass's public interface to have that method, then you implement the interface explicitly. That's the whole idea of the approach. This means the following is not allowed:

MyClass a = new MyClass();
a.Convert();

However, the following is still be allowed:

MyClass a = new MyClass();
((IConvertible)a).Convert();

The whole idea behind this is that even though we're using the exact same instance, a as MyClass doesn't have the method. A as IConvertible does have the method. Think of it as if you're allowing the instance to have split personality.

Usually I end implementing every interface implicitly. However, there are very specific situations where I'd implementing them explicitly exactly for the reasons outlined above.

BTW, thanks for the great question!

like image 182
Rui Craveiro Avatar answered Oct 21 '22 15:10

Rui Craveiro


Because explicit interface implementation actually hides the implementation.

like image 20
abatishchev Avatar answered Oct 21 '22 15:10

abatishchev