C# How to restrict interface properties - c#

I have one interface which is inherited by a few classes, some of the properties however are being set only by the constructor of the classes. I will never change the values of those properties outside of the constructor so I want to restrict the properties by having them with a private setter, but the interface doesn't allow me to use properties with any type of modifiers how can i work around this ?

Interfaces are there to describe things that any implementing type must be able to do. It's not capable of defining thinks that it can't do.
The interface can define that there must be a given property getter of an appropriate name and type, but it can't specify that there must not be a public setter for that property.
You're certainly welcome to provide documentation with this interface suggesting that implementors have a private setter, or even that they never allow the value to change outside of a constructor, but there's no way for an interface to specify such a constraint.

There is no way to enforce immutability for these properties on a compiler and language level.
In other words, there is no way for you to write your interface such that immutability for these properties is the only thing that is allowed, nor that they don't have a public setter in the class.
The language simply does not have any syntax which allows you to express this requirement.
You can declare the properties in your interface without setters but you cannot require the actual properties in the implementation to
Have no setters
Never change their value
Please note that if you only expose the implementation classes through the interface then only the access methods you declare in the interface will be available. In other words, if your interface only declares a getter, you cannot set the value through the interface.
Your best option is simply to document this part of the interface contract and hope that whoever implements this interface follows your intent and guideline.

In your interface specify only a getter:
interface ISomeInterface
{
int SomeProperty { get; }
}
Your implementations are free to set it privately:
class Foo : ISomeInterface
{
public int SomeProperty { get; private set; }
public Foo()
{
SomeProperty = 42;
}
}

You can do this by using a readonly struct instead of a class. Of course there are a lot of drawbacks, such as not being able to use an interface (at least not without boxing) and having to use copy semantics (which are slower if the struct is large).
By using a readonly struct you can require that the properties are immutable.

Related

Readonly field vs abstract getter-only property

What are the advantages and disadvantages of having a readonly field compared to having inheritors implement an abstract getter-only property (using C# as an example here, but I guess that doesn't really matter much).
Here are both ways to do this:
readonly field; inheritors have to inject the value in the constructor
interface IFace {
public int Field { get; }
}
abstract class Base : IFace {
private readonly int field;
protected Base(int field) {
this.field = field;
}
public int Field { get { return this.field; } }
}
class Impl {
public Impl() : base(1) {
}
}
abstract getter-only property; inheriters have to implement the property
interface IFace {
public int Field { get; }
}
abstract class Base : IFace {
// default constructor can be used
public abstract int Field { get; }
}
class Impl {
public override int Field { get { return 1; } }
}
Both implementations expose a public int Field getter-only property which does not change.
However, I can see the following differences:
The value of field is bound to each instance and there's nothing preventing inheritors from allowing to receive the value in their constructors themselves (public Impl(int field) : base(field)).
Being bound to an instance, memory for the field is required for each single instance. Which might not be a big deal, but it's definitely something to keep in mind.
The conveyed intent is: the value can only be set in the constructor and cannot change later on (leaving aside reflection).
The (returned) value of Field is bound to each type, but there's nothing preventing inheritors from generating/calculating the value each time the getter is called, potentially returning a different value each time. public overried int Field { get { return DateTime.UtcNow.Second; } }
Memory is only required "in IL", since the value is (usually) not stored anywhere, but always computed before being returned (resulting in a load instruction and nothing more).
The conveyed intent should be: the value is bound to the type (and shouldn't change between calls, but there's no way to force that, right?). But rather the intent comes across as: you need to provide this property, I don't care how you implement it and which value it returns.
Are there any crucial differences I'm missing? Is one preferred over the other, or is it required to decide on a case-by-case basis?
I guess I'm looking for a construct/pattern/language feature which binds readonly (constant) values to a type, but expose the value at the instance level. I know that I can use static fields in each inheriting type, but there's no way to enforce this from a common base (or interface). Furthermore, static fields cannot be called when having only a reference to an instance of this type. Thoughts? I'm happy to receive answers in different programming languages
There is one crucial difference between pattern 1 and pattern 2 you have given.
Pattern 1 does not allow to return a different value once class is constructed because base class takes field only in constructor.
Pattern 2 allows child classes to return different values at different times. Basically - there is nothing enforced from base class if child class decides to override.
Thus - it really depends what you want to achieve and your domain logic.
Regarding the intent you are trying to achieve - in my opinion - one of the ways to tackle the implement the intention is declare a virtual method (something like getReadOnlyField() in base) rather than a read-only property. Then - child classes are free to override the virtual method - if they do not override - base implementation will still be enforced.
There cannot be any one right answer to this question. There will be multiple ways to resolve this. It all depends on your requirements.
I believe that readonly-fields and abstract-getters are two completely different concepts. The readonly-field is all about how the field should be used within the class it is defined in.
An abstract-getter is all about the interface of the class. It does not put any restrictions on how the variable is used, but it forces all class inheritors to implement the getter in order to meet the interface.
The actual question should be where to locate the public getter of the public int Field property; should it be on the base or on the inheriting class? The answer (in my option) depends on whether the base class has to know the actual value of the Field property. If so, place it on the base, otherwise just force all child classes to implement the property getter.
Your abstraction defines a contract that implementors have to comply with. That goes beyond implementing methods with the correct signatures etc. Violating it means breaking the liskov substitution principle, i.e. asking for subtle or not so subtle bugs.
I can understand if someone feels the contract must be enforced somehow, but in the end you cannot enforce complying with LSP. You can only make the intention as clear as possible by using proper documentation and usually unit tests which document behavior as well. And keep in mind that developers usually don't violate contracts or LSP on purpose. If developers have malicious intent, all bets are off anyway.
That being said, I'd say there is no actual difference in the cases you stated. Yes, the implementations are syntactically and semantically different, but other classes would only depend on IFace anyway, right? Seriously, there's no excuse to depend on concrete implementations if there already is an abstraction. So nothing stops anyone from creating a new implementation for IFace and pass that around.

implementing interface methods c# [duplicate]

What are the differences in implementing interfaces implicitly and explicitly in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.
Here's an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.
Reason #1
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Reason #2
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
The class's primary interface, which is used by web page developers; and
A "hidden" interface used by the presenter that I develop to handle the control's logic
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
But's It's Not a Silver Cannonball
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to
understand some ramifications that
exist when using EIMIs. And because of
these ramifications, you should try to
avoid EIMIs as much as possible.
Fortunately, generic interfaces help
you avoid EIMIs quite a bit. But there
may still be times when you will need
to use them (such as implementing two
interface methods with the same name
and signature). Here are the big
problems with EIMIs:
There is no documentation explaining how a type specifically
implements an EIMI method, and there
is no Microsoft Visual Studio
IntelliSense support.
Value type instances are boxed when cast to an interface.
An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
When required, as per disambiguation or needing an internal interface
Discourages "programming to an implementation" (Reason 1 by Jon)
Problems
It's not all fun and happiness. There are some cases where I stick with implicits:
Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
(My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).
In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
This code compiles and runs OK, but the Title property is shared.
Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.
Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.
If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.
Public Overridable Function Foo() As Integer Implements IFoo.Foo
Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
Not as nice.
The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.
// Given:
internal interface I { void M(); }
// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }
// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }
The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.
Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
I've found myself using explicit implementations more often recently, for the following practical reasons:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways
Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI
No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too
Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync

C# class design - what can I use instead of "static abstract"?

I want to do the following
public abstract class MyAbstractClass
{
public static abstract int MagicId
{
get;
}
public static void DoSomeMagic()
{
// Need to get the MagicId value defined in the concrete implementation
}
}
public class MyConcreteClass : MyAbstractClass
{
public static override int MagicId
{
get { return 123; }
}
}
However I can't because you can't have static abstract members.
I understand why I can't do this - any recommendations for a design that will achieve much the same result?
(For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes, there are good reasons for keeping it static.)
You fundamentally can't make DoSomeMagic() work with the current design. A call to MyConcreteClass.DoSomeMagic in source code will be translated into MyAbstractClasss.DoSomeMagic in the IL. The fact that it was originally called using MyConcreteClass is lost.
You might consider having a parallel class hierarchy which has the same methods but virtual - then associate each instance of the original class with an instance of the class containing the previously-static members... and there should probably only be one instance of each of those.
Would the Singleton pattern work perhaps? A link to the MSDN article describing how to implement a singleton in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In your particular example, the Singelton instance could extend an abstract base class with your MagicId in it.
Just a thought :)
I would question that there are "good reasons" for making the abstract members static.
If your thinking is that these members might reflect some property of the derived class itself rather than a given instance, this does not necessarily mean the members should be static.
Consider the IList.IsFixedSize property. This is really a property of the kind of IList, not any particular instance (i.e., any T[] is going to be fixed size; it will not vary from one T[] to another). But still it should be an instance member. Why? Because since multiple types may implement IList, it will vary from one IList to another.
Consider some code that takes any MyAbstractClass (from your example). If this code is designed properly, in most cases, it should not care which derived class it is actually dealing with. What matters is whatever MyAbstractClass exposes. If you make some abstract members static, basically the only way to access them would be like this:
int magicId;
if (concreteObject is MyConcreteClass) {
magicId = MyConcreteClass.MagicId;
} else if (concreteObject is MyOtherConcreteClass) {
magicId = MyOtherConcreteClass.MagicId;
}
Why such a mess? This is much better, right?
int magicId = concreteObject.MagicId;
But perhaps you have other good reasons that haven't occurred to me.
Your best option is to use an interface with MagicId only using a setter
public interface IMagic
{
int MagicId { get; }
}
By the nature of Static meaning there can only be one (yes like Highlander) you can't override them.
Using an interface assumes your client will implement the contract. If they want to have an instance for each or return the value of a Static variable it is up to them.
The good reason for keeping things static would also mean you do NOT need to have it overridden in the child class.
Not a huge fan of this option but...
You could declare the property static, not abstract, virtual and throw a NotImplementedException which returns an error message that the method has to be overridden in a derived class.
You move the error from compile time to run time though which is kinda ugly.
Languages that implement inheritance of static members do it through metaclasses (that is, classes are also objects, and these objects have a metaclass, and static inheritance exists through it). You can vaguely transpose that to the factory pattern: one class has the magic member and can create objects of the second class.
That, or use reflection. But you can't ensure at compile-time that a derived class implements statically a certain property.
Why not just make it a non-static member?
Sounds like a Monostate, perhaps? http://c2.com/cgi/wiki?MonostatePattern
The provider pattern, used by the ASP.NET membership provider, for example, might be what you're looking for.
You cannot have polymorphic behavior on static members, so you'll have a static class whose members delegate to an interface (or abstract class) field that will encapsulate the polymorphic behaviors.

C# syntax: Placing the interface's name in the implementation's declaration

I came across some interesting C# syntax that I'm not familiar with in the source code for the Composite Application Library for WPF's DelegateCommand<T> class.
There are some method declarations which are prefixed with the ICommand interface name, and they do not have accessibility modifiers specified. For example:
bool ICommand.CanExecute(object parameter) { ... }
What is this syntax called and where can I read more about it? I assume there's an implicit public, but I can't figure out what the benefit of specifying the class name is. My guess is that it might just be there for organization.
When you place a method like this, you're saying that this is the explicit implementation of the interface. You can read a good tutorial on MSDN via that link.
Also, a comparison might be helpful for a full view of what this means.
It's termed Explicit Interface Implementation:
If a class implements two interfaces
that contain a member with the same
signature, then implementing that
member on the class will cause both
interfaces to use that member as their
implementation.
If the two interface members do not
perform the same function, however,
this can lead to an incorrect
implementation of one or both of the
interfaces. It is possible to
implement an interface member
explicitly—creating a class member
that is only called through the
interface, and is specific to that
interface. This is accomplished by
naming the class member with the name
of the interface and a period.
Explicit Interface Implementation Tutorial
This is called explicit interface implementation and you can read about it here.
The basic idea is that those methods/properties are only accessable when explicitly used via an interface instance of that type.
It is called explicit implementation of interfaces. What it means is that this particular implementation of CanExecute will not be visible (and will not run) UNLESS the object is cast as an ICommand.
This can be useful in allowing a class to provide different implementations for different interfaces where method names overlap
public interface InterfaceOne {
void SomeMethod();
}
public interface InterfaceTwo {
void SomeMethod();
}
public class Impl : InterfaceOne, InterfaceTwo {
public void InterfaceOne.SomeMethod() {Console.WriteLine("One");}
public void InterfaceTwo.SomeMethod() {Console.WriteLine("Two");}
}
I personally hate this this syntax. Take the example of OracleParameter which provides only an explicit implementation of ICloneable.
If you have a reference to OracleParameter, the Clone() method will not appear in intellisense and will not be visible when you "Go To Definition". However the ability IS there if you do ((ICloneable)parameter).Clone(). In order to even know that this is possible, you can do that you are pretty much stuck googling around in blogs.
This is called explicit interface implementation and you can read more about it here.
In Visual Studio, if you inherit from an interface, you can right-click on the interface name in your class definition. You can click either "Implement Interface", or in the submenu, "Implement Interface Explicitly". This is a handy shortcut for implementing interfaces.

C# Interfaces. Implicit implementation versus Explicit implementation

What are the differences in implementing interfaces implicitly and explicitly in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.
Here's an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.
Reason #1
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Reason #2
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
The class's primary interface, which is used by web page developers; and
A "hidden" interface used by the presenter that I develop to handle the control's logic
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
But's It's Not a Silver Cannonball
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to
understand some ramifications that
exist when using EIMIs. And because of
these ramifications, you should try to
avoid EIMIs as much as possible.
Fortunately, generic interfaces help
you avoid EIMIs quite a bit. But there
may still be times when you will need
to use them (such as implementing two
interface methods with the same name
and signature). Here are the big
problems with EIMIs:
There is no documentation explaining how a type specifically
implements an EIMI method, and there
is no Microsoft Visual Studio
IntelliSense support.
Value type instances are boxed when cast to an interface.
An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
When required, as per disambiguation or needing an internal interface
Discourages "programming to an implementation" (Reason 1 by Jon)
Problems
It's not all fun and happiness. There are some cases where I stick with implicits:
Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
(My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).
In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
This code compiles and runs OK, but the Title property is shared.
Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.
Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.
If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.
Public Overridable Function Foo() As Integer Implements IFoo.Foo
Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
Not as nice.
The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.
// Given:
internal interface I { void M(); }
// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }
// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }
The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.
Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
I've found myself using explicit implementations more often recently, for the following practical reasons:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways
Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI
No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too
Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync

Categories

Resources