I've struck upon something I don't really understand.
I have a project, where I have an interface that is internal. The class that implements that interface is also internal. In the implementation of the interface, I make all the members that I implement, internal. I did not do an explicit implementation.
I have two interfaces and two classes that implement those interfaces where this works fine.
It would look something like this:
internal interface IA
{
void X();
}
and then
internal class CA : IA
{
internal void X()
{
...
}
}
This works fine for the two aforementioned classes. But when I try to do it with another interface and class, it doesn't work. In fact, for the example above, I get the error:
'WindowsFormsApplication1.CA' does not implement interface member 'WindowsFormsApplication1.IA.X()'. 'WindowsFormsApplication1.CA.X()' cannot implement an interface member because it is not public.
I realize I can make the methods public or do an explicit implementation (and omit the internal and public modifiers), but I'm simply confused as to why it works with the two classes it works with and yet I seem to be unable to replicate it anywhere else.
Butchering the code a bit (because it's confidential), this is one of the ones that actually works in my project.
internal interface IScanner
{
void SetHardware(Hardware hardware);
void Start();
void PauseScan();
void ResumeScan();
void Stop();
bool InScan { get; }
event ScanCompleteHandler ScanComplete;
}
Then I have the class:
internal class MyScanner : IScanner
{
internal void SetHardware(Hardware hardware)
{
...
}
internal void Start()
{
...
}
internal void Stop()
{
...
}
internal void PauseScan()
{
...
}
internal void ResumeScan()
{
...
}
internal bool InScan
{
get
{
...
}
}
internal event ScanCompleteHandler ScanComplete;
}
To make things even stranger, I created another internal class called Temp. I then had it implement the IScanner interface and I copied and pasted the implementation from MyScanner over to it and it won't compile, giving me the error that: "cannot implement an interface member because it is not public."
Can anyone explain this inconsistency?
Thanks
(Updated to fix a typo and clarify some text)
EDIT: Additional Information
I ran the code through reflector and my implementations have been compiled as explicit implementations, even though they aren't explicit. Reflector shows no signs of the internal keywords. All I can guess is that this is some sort of glitch in the compiler that, for some reason, allowed me to make them internal and implicit and that it somehow resolved that as being an explicit implementation.
I've looked over the code a number of times. I can't find any other explanation for it.
If you are implicitly implementing an interface I believe that the member must be declared public. In your example, CA attempts to implicitly implement the X() method but isn't declared public. If you want to keep X() as internal then you should use explicit interface implementation.
void IA.X() { /* stuff */ }
However, I'll also add that making the X() method public wouldn't do any harm anyway as the class is internal so that member is already restricted by that access modifier... That is, it's already effectively internal... So you might as well just make it public!
I know it has been a while since this question was asked, but maybe I can shed some light on it. According to the C# language specification found here the behavior you described should not be possible. Because under 20.4.2 Interface mapping it is said that the implementation is either explicit or mapped to a public non-static member. So either you have some other scenario than the one you are describing here, or you found a bug in your compiler :).
Probably that your "Temp" class is public and IScanner is internal. This is the reason why you get this error. I consider this very annoying since your are forced to implement it explicitly you cannot specify them as abstract or virtual. For the virtual stuff, I was forced to do an implicit internal virtual implementation of the same API and then call the implicit version from the explicit one. Ugly.
If your intention is to hide a certain implementation from outside, you can implement it explicitly like this:
internal class LDialogService : ILDialogService, ILDialogInternalService
{
public async Task<TValue> ShowAsync<TValue>(ILDialogFragment fragment)
{
throw new NotImplementedException();
}
void ILDialogInternalService.SetComponent(LDialog component)
{
throw new NotImplementedException();
}
}
In the above code, I want to expose ShowAsync method to the outside but keep SetComponent inside. Since ILDialogInternalService is internal, no one can call it from outside except through Reflection.
To all my knowledge you cannot implement interface methods internal. As you stated you can implement them explicitly but then someone can still do ((IScanner)myScanner).SetHardware(hw)
Are you 100% sure your MyScanner implementation does not do something like this:
internal class MyScanner : IScanner
{
void IScanner.SetHardware(Hardware hardware) { this.SetHardware(hardware); }
internal void SetHardware(Hardware hardware)
{
...
}
....
}
or this:
internal partial class MyScanner : IScanner
{
internal void SetHardware(Hardware hardware)
{
...
}
}
internal partial class MyScanner
{
void IScanner.SetHardware(Hardware hardware)
{
this.SetHardware(hardware);
}
}
It's OK to have an internal modifier in an Interface declaration however you CAN'T have ANY modifiers INSIDE the interface, in other words, you can't have any modifier for the interface Members. It's simple as that!
Example:
internal interface IA
{
void X(); //OK. It will work
}
internal class CA : IA
{
**internal** void X() // internal modifier is NOT allowed on any Interface members. It doesn't compile. If it works in your project it's because either you DON'T have the void X() method in the Interface or your are inheriting from a wrong interface maybe accidentally
{
...
}
}
An interface declaration may declare zero or more members. The members of an interface must be methods, properties, events, or indexers. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types, nor can an interface contain static members of any kind.
All interface members implicitly have public access. It is a compile-time error for interface member declarations to include any modifiers. In particular, interfaces members cannot be declared with the modifiers abstract, public, protected, internal, private, virtual, override, or static.
Reference:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/interfaces
Related
is this possible to create a private members in interface in .NET? I heard that it is possible now but I my IDE is rejecting it:
public interface IAnimal
{
void SetDefaultName(string name)
{
ChangeName(name);
}
private string defaultName = "NoName";
private void ChangeName(string name)
{
defaultName = name;
}
void Breath()
{
Console.WriteLine($"Default - I'm {defaultName}. <Breathing sounds>");
}
void Sound();
}
Yes! Now you can in C# 8.0 but it has to be a static member. Like this:
public interface IAnimal
{
static void SetDefaultName(string name)
{
ChangeName(name);
}
private static string defaultName = "NoName";
private static void ChangeName(string name)
{
defaultName = name;
}
void Breath()
{
Console.WriteLine($"Default - I'm {defaultName}. <Breathing sounds>");
}
void Sound();
}
But you need to keep in mind that static fields will be shared across the application. Changing the defaultName will result in changing it in every place where you are using IAnimal
private methods used to be prohibited in interfaces because interfaces are supposed to be contracts. They are a guarantee that "this class has the following methods and properties". Why would it be useful to guarantee that a class has a private method? It isn't useful, because no one else can call it!
In C# 8, this changed. You can now specify private interface default methods. Note that it has to be a default method, not the ones that doesn't have an implementation. Here's the docs stating that fact:
The syntax for an interface is relaxed to permit modifiers on its members. The following are permitted: private, protected, internal, public, virtual, abstract, sealed, static, extern, and partial.
...
It is an error for a private or sealed function member of an interface to have no body.
Here is a quote from the docs explaining why this is allowed:
Static and private methods permit useful refactoring and organization of code used to implement the interface's public API.
The actual question should be : should i do (or be able to do) it or not ?
The whole idea of the interface thing is to provide abstraction .
private members usually are implementation details that the consumer of your code shouldn't care about or know they exists so they don't belong to your abstract layer (interface)
the interface is the facade that the consumer will interact with ur service/component thorough , it should contain only the methods that the consumer will call , this is why originally interfaces should have only public modifiers
not to mention that putting such members in the interface will force every implementation of it to implement these members even if they don't need it
from my opinion the only reason C# changed interfaces and made them allow implementation is to make up for the language lack of support for multiple class inheritance , but that does mean that you should miss use ur interfaces like that
Yes, with C# 8.0, you can have public, private and protected members.
For example, following works:
public interface ITest
{
private SomeEnum EnumTy { get => SomeEnum.Value1; }
}
If a class implements an interface and tries to access the variable, they will get an error.
public class TestImpl : ITest
{
ITest.EnumTy = SomeEnum.Value2; // gives an error
}
The members can also be protected. As a suggestion, going forward its good to have public before methods to indicate more readability (even though public is default).
A good article is here:
https://jeremybytes.blogspot.com/2019/11/c-8-interfaces-public-private-and.html
I'm looking for a way to share the implementation of two classes without exposing any details of that sharing. I was hoping to create this basic class structure:
public interface MyInterface
class MyCommonImpl : MyInterface
public class MyImplA : MyCommonImpl
public class MyImplB : MyCommonImpl
MyCommonImpl implements the functions of MyInterface and has one abstract function provided in MyImplA and MyImplB. A user of MyImplA should not know about MyCommonImpl in any fashion, it's just an implentation detail.
I've considered doing manual composition, but this involves copying a lot of code to forward the functions. It's also problematic since there are events implemented in MyCommonImpl, and one of their parameters is a sender. This requires putting a proxy handler and partially rewriting events. Basically composition would require more code than simply copy-pasting the entire MyCommonImpl.
How can I do this without having to duplicate a lot of code?
You can move the interfaces and implementations to another assembly and mark them internal which will hide the abstract function of MyCommonImpl. Taking it further, you could explicitly implement the interfaces inside that assembly to completely hide their methods from callers leaving only those methods declared public on MyImplA visible.
The internal casts for the explicit implementation are a bit nasty though...
In a separate assembly:
namespace Private
{
internal interface IMyInterface
{
void InterfaceMethod();
}
public abstract class MyCommonImpl : IMyInterface
{
internal MyCommonImpl()
{
// internal ctor to stop callers constructing
}
void IMyInterface.InterfaceMethod()
{
Console.WriteLine("InterfaceMethod");
}
internal abstract void CommonAbstract();
}
public class MyImplA : MyCommonImpl
{
internal override void CommonAbstract()
{
((IMyInterface)this).InterfaceMethod();
Console.WriteLine("CommonAbstract");
}
public void ImplAMethod()
{
CommonAbstract();
Console.WriteLine("ImplAMethod");
}
}
}
In C++, you can do the following:
class base_class
{
public:
virtual void do_something() = 0;
};
class derived_class : public base_class
{
private:
virtual void do_something()
{
std::cout << "do_something() called";
}
};
The derived_class overrides the method do_something() and makes it private. The effect is, that the only way to call this method is like this:
base_class *object = new derived_class();
object->do_something();
If you declare the object as of type derived_class, you can't call the method because it's private:
derived_class *object = new derived_class();
object->do_something();
// --> error C2248: '::derived_class::do_something' : cannot access private member declared in class '::derived_class'
I think this is quite nice, because if you create an abstract class that is used as an interface, you can make sure that nobody accidentally declares a field as the concrete type, but always uses the interface class.
Since in C# / .NET in general, you aren't allowed to narrow the access from public to private when overriding a method, is there a way to achieve a similar effect here?
If you explicitly implement an interface, this will at least encourage people to use the interface type in the declaration.
interface IMyInterface
{
void MyMethod();
}
class MyImplementation : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
One will only see MyMethod after casting the instance to IMyInterface. If the declaration uses the interface type, there is no casting needed in subsequent uses.
MSDN page on explicit interface implementation (thanks Luke, saves me a few seconds^^)
IMyInterface instance = new MyImplementation();
instance.MyMethod();
MyImplementation instance2 = new MyImplementation();
instance2.MyMethod(); // Won't compile with an explicit implementation
((IMyInterface)instance2).MyMethod();
You can do this in the .Net world too, using explicit interface implementation
As an example, BindingList<T> implements IBindingList, but you have to cast it to IBindingList to see the method.
You are able to decrease a method's availability by marking it as new.
The example from MSDN's CA2222: Do not decrease inherited member visibility:
using System;
namespace UsageLibrary
{
public class ABaseType
{
public void BasePublicMethod(int argument1) {}
}
public class ADerivedType:ABaseType
{
// Violates rule: DoNotDecreaseInheritedMemberVisibility.
// The compiler returns an error if this is overridden instead of new.
private new void BasePublicMethod(int argument1){}
}
}
This is really more interesting as an academic exercise; if your code is truly dependent on not being able to call BasePublicMethod on ADerivedType, that's a warning sign of a dubious design.
The problem with this strategy, should it be implemented, is that the method is not truly private. If you were to upcast a reference to base_class, then the method is now public. Since it's a virtual method, user code will execute derived_class::do_something() eventhough it's marked as private.
This question already has answers here:
C# Interfaces. Implicit implementation versus Explicit implementation
(13 answers)
Closed 7 years ago.
What's the difference between Explicitly implement the interface and Implement the interface.
When you derive a class from an interface, intellisense suggest you to do both.
But, what's the difference?
Another aspect of this:
If you implicitly implemented, it means that the interface members are accessible to users of your class without them having to cast it.
If it's explicitly implemented, clients will have to cast your class to the interface before being able to access the members.
Here's an example of an explicit implementation:
interface Animal
{
void EatRoots();
void EatLeaves();
}
interface Animal2
{
void Sleep();
}
class Wombat : Animal, Animal2
{
// Implicit implementation of Animal2
public void Sleep()
{
}
// Explicit implementation of Animal
void Animal.EatRoots()
{
}
void Animal.EatLeaves()
{
}
}
Your client code
Wombat w = new Wombat();
w.Sleep();
w.EatRoots(); // This will cause a compiler error because it's explicitly implemented
((Animal)w).EatRoots(); // This will compile
The IDE gives you the option to do either - it would be unusual to do both. With explicit implementation, the members are not on the (primary) public API; this is handy if the interface isn't directly tied to the intent of the object. For example, the ICustomTypeDescriptor members aren't all that helpful to regular callers - only to some very specific code, so there is no purpose having them on the public API causing mess.
This is also useful if:
there is a conflict between an interface's Foo method and your own type's Foo method, and they mean different things
there is a signature conflict between other interfaces
The typical example of the last point is IEnumerable<T>, which has a GetEnumerator() method at two levels in the interface hierarchy - it is common to implement the typed (IEnumerator<T>) version using implicit implementation, and the untyped (IEnumerator) version using explicit implementation.
Here's the difference in plain English:
Suppose you have an interface Machine, which has a function Run(), and another interface Animal which also has a function called Run(). Of course, when a machine runs, we're talking about it starting up, but when an animal runs, we're talking about it moving around. So what happens when you have an object, lets call it Aibo that is both a Machine and an Animal? (Aibo is a mechanical dog, by the way.) When Aibo runs, does he start up, or does move around? Explicitly implementing an interface lets you make that distinction:
interface Animal
{
void Run();
}
interface Machine
{
void Run();
}
class Aibo : Animal, Machine
{
void Animal.Run()
{
System.Console.WriteLine("Aibo goes for a run.");
}
void Machine.Run()
{
System.Console.WriteLine("Aibo starting up.");
}
}
class Program
{
static void Main(string[] args)
{
Aibo a = new Aibo();
((Machine)a).Run();
((Animal)a).Run();
}
}
The catch here is that I can't simply call a.Run() because both of my implementations of the function are explicitly attached to an interface. That makes sense, because otherwise how would the complier know which one to call? Instead, if I want to call the Run() function on my Aibo directly, I'll have to also implement that function without an explicit interface.
Explicit will put IInterfaceName. at the front of all of the interface implementations. It's useful if you need to implement two interfaces that contain names/signatures that clash.
More info here.
Explicitly implement puts the fully qualified name on the function name consider this code
public interface IamSam
{
int foo();
void bar();
}
public class SamExplicit : IamSam
{
#region IamSam Members
int IamSam.foo()
{
return 0;
}
void IamSam.bar()
{
}
string foo()
{
return "";
}
#endregion
}
public class Sam : IamSam
{
#region IamSam Members
public int foo()
{
return 0;
}
public void bar()
{
}
#endregion
}
IamSam var1;
var1.foo() returns an int.
SamExplicit var2;
var2.foo() returns a string.
(var2 as IamSam).foo() returns an int.
Here you go, directly from MSDN
The difference is that you can inherit a class from several interfaces. These interfaces may have identical Method signatures. An explicit implementation allows you to change your implementation according to which Interface was used to call it.
Explicit interface implementation, where the implementation is hidden unless you explicitly cast, is most useful when the interface is orthogonal to the class functionality. That is to say, behaviorally unrelated .
For example, if your class is Person and the interface is ISerializable, it doesn't make much sense for someone dealing with Person attributes to see something weird called 'GetObjectData' via Intellisense. You might therefore want to explicitly implement the interface.
On the other hand, if your person class happens to implement IAddress, it makes perfect sense to see members like AddressLine1, ZipCode etc on the Person instances directly (implicit implementation).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
In C#, when you implement an interface, all members are implicitly public. Wouldn't it be better if we could specify the accessibility modifier (protected, internal, except private of course), or should we just use an abstract class instead?
If an interface is internal, all its members will be internal to the assembly. If a nested interface is protected, only the subclasses of the outer class could access that interface.
Internal members for an interface outside of its declaring assembly would be pointless, as would protected members for an interface outside of its declaring outer class.
The point of an interface is to describe a contract between a implementing type and users of the interface. Outside callers aren't going to care and shouldn't have to care about implementation, which is what internal and protected members are for.
For protected members that are called by a base class, abstract classes are the way to go for specifying a contract between base classes and classes that inherit from them. But in this case, implementation details are usually very relevant, unless it's a degenerate pure abstract class (where all members are abstract) in which case protected members are useless. In that case, go with an interface and save the single base class for implementing types to choose.
You can hide the implementation of an interface by explicitly stating the interface name before the method name:
public interface IInterface {
public void Method();
}
public class A : IInterface {
public void IInterface.Method() {
// Do something
}
}
public class Program {
public static void Main() {
A o = new A();
o.Method(); // Will not compile
((IInterface)o).Method(); // Will compile
}
}
Would not make sense. An Interface is a contract with the public that you support those methods and properties. Stick with abstract classes.
All the answers here more or less say that's how interfaces are meant to be, they are universal public specifications.
This being the most discussed thread, let me post two excellent answers I found on SO when this question surfaced my mind.
This answer gives an example of how it can be nonsensical to have non uniform access specifiers for interface members in derived classes. Code always better than technical descriptions.
To me the most damning thing about forced public interface members are that the interface itself can be internal to an assembly but the members it exposes have to be public. Jon Skeet explains here that's by design sadly.
That raises the question why weren't interfaces designed to have non-public definitions for members. That can make the contract flexible. This is pretty useful when writing assemblies where you dont want specific members of classes to be exposed to outside the assembly. I do not know why.
An interface is a contract that all implementing classes adhere to. This means that they must adhere to all of it or none of it.
If the interface is public then every part of that contact has to be public, otherwise it would mean one to friend/internal classes and a different thing to everything else.
Either use an abstract base class or (if possible and practical) an internal extension method on the interface.
You can hide almost all of the code implemented by interfaces to external assemblies.
interface IVehicle
{
void Drive();
void Steer();
void UseHook();
}
abstract class Vehicle // :IVehicle // Try it and see!
{
/// <summary>
/// Consuming classes are not required to implement this method.
/// </summary>
protected virtual void Hook()
{
return;
}
}
class Car : Vehicle, IVehicle
{
protected override void Hook() // you must use keyword "override"
{
Console.WriteLine(" Car.Hook(): Uses abstracted method.");
}
#region IVehicle Members
public void Drive()
{
Console.WriteLine(" Car.Drive(): Uses a tires and a motor.");
}
public void Steer()
{
Console.WriteLine(" Car.Steer(): Uses a steering wheel.");
}
/// <summary>
/// This code is duplicated in implementing classes. Hmm.
/// </summary>
void IVehicle.UseHook()
{
this.Hook();
}
#endregion
}
class Airplane : Vehicle, IVehicle
{
protected override void Hook() // you must use keyword "override"
{
Console.WriteLine(" Airplane.Hook(): Uses abstracted method.");
}
#region IVehicle Members
public void Drive()
{
Console.WriteLine(" Airplane.Drive(): Uses wings and a motor.");
}
public void Steer()
{
Console.WriteLine(" Airplane.Steer(): Uses a control stick.");
}
/// <summary>
/// This code is duplicated in implementing classes. Hmm.
/// </summary>
void IVehicle.UseHook()
{
this.Hook();
}
#endregion
}
This will test the code.
class Program
{
static void Main(string[] args)
{
Car car = new Car();
IVehicle contract = (IVehicle)car;
UseContract(contract); // This line is identical...
Airplane airplane = new Airplane();
contract = (IVehicle)airplane;
UseContract(contract); // ...to the line above!
}
private static void UseContract(IVehicle contract)
{
// Try typing these 3 lines yourself, watch IDE behavior.
contract.Drive();
contract.Steer();
contract.UseHook();
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
}
Interfaces do not have access modifiers in their methods, leaving them open to whichever access modifier is appropriate. This has a purpose: it allows other types to infer what methods and properties are available for an object following an interface. Giving them protected/internal accessors defeats the purpose of an interface.
If you are adamant that you need to provide an access modifier for a method, either leave it out of the interface, or as you said, use an abstract class.
I'm familiar with Java rather than C#, but why an earth would you want a private member within an interface? It couldn't have any implementation and would be invisible to implementing classes, so would be useless. Interfaces exist to specify behaviour. If you need default behaviour than use an abstract class.
In my opintion this violates encapsulation. I have to implement a methos as public then I implement an interface. I see no reason to force public in a class that impletements the interface. (c#)