Why will my interface not implement a public method? - c#

Why will my interface not import into my class? I just want to test some interfaces and need to have the one method extended into my class that implements my interface. This I thought would be simple but it is throwing me an error which I will list at the bottom. My method is public and it is throwing me and error. In fact I took the public keyword away and it is still throwing me an error.
Is there a short cut key to import all of the methods into a class.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlowControl
{
public abstract class Grades : iBase, iFoot
{
public abstract void AddGrade(float grade);
public abstract void ComputeStatistics();
public void WriteGrades(string t)
{
}
public int AddTwo(int a, int b)
{
return 0;
}
void findYourScore() { }
}
public interface iBase
{
public void findYourScore();
}
public interface iFoot
{
}
}
But I get this error:
The modifier 'public' is not valid for this item

You can't specify access modifiers on interface methods, properties, events, or indexers. The interface itself is marked public, therefore all of its members are also implicitly public. However, you will have to specify an access modifier where you're implementing the method (unless you're writing an explicit interface member implementation).
For example:
public abstract class Grades : iBase, iFoot
{
...
public void findYourScore() { }
}
public interface iBase
{
void findYourScore();
}
Further Reading
interface (C# Reference)
Interfaces (C# Programming Guide)

You can't specify the access modifiers inside of interface.You just need to specify signature of the method
public interface iBase
{
void findYourScore();
}
From documentation:
Interfaces can contain methods, properties, events, indexers, or any combination of those four member types. An interface can't contain constants, fields, operators, instance constructors, destructors, or types. Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.

It is as simple as
public interface iBase
{
void findYourScore();
}
Interface members don't need access qualifiers. public is then not valid in this context, as the compiler says.

Interfaces do not specify the protection levels or methods and do not implement them either. Removes the public/private piece and your code will work fine. Classes which implement an interface determine what the access level is. If you need to specify access level use an abstract class instead of an interface.

Related

If we cannot use access-protected modifiers within an interface what are the options?

As the title says: If we cannot use access-protected modifiers within an interface then what can we use in c#?
The only answer found is to use an abstract class?
Interface members are required to be public.
If you need members with access modifiers that you are required to implement in the child class, use abstract members in a parent class.
abstract class BaseClass
{
protected abstract SomeMethod();
}
class Child : BaseClass
{
// You will be required to implement SomeMethod() or declare abstract.
}
Interfaces don't allow member access modifiers but the interfaces themselves can have any access modifier valid for a regular class. This used jointly with explicitly implemented interfaces allows, in a way, member level access modifiers. Consider the following code:
internal interface IFoo
{
void Frob();
}
public interface IBar
{
void Blah();
}
public class Foo : IFoo, IBar
{
void IFoo.Frob() { }
public void Blah() { }
}
And you essentially have the moral equivalent of a hypothetical:
public interface IFooBar
{
public void Blah();
internal void Frob();
}
Although it is true that there is no way around the fact that Frob must be implemented explicitly, at least as c# stands today.

Understanding Interfaces C#

Been reading all day on interfaces and abstract classes trying to get a grasp on them to better understand the amazon library I'm working with. I have this code:
using MWSClientCsRuntime;
namespace MarketplaceWebServiceOrders.Model
{
public interface IMWSResponse : IMwsObject
{
ResponseHeaderMetadata ResponseHeaderMetadata { get; set; }
}
and
namespace MWSClientCsRuntime
{
public interface IMwsObject
{
void ReadFragmentFrom(IMwsReader r);
string ToXML();
string ToXMLFragment();
void WriteFragmentTo(IMwsWriter w);
void WriteTo(IMwsWriter w);
}
}
My first questions is I thought Interfaces cannot contain fields, however they can contain properties usch as ResponseHeaderMetadata?
Second, in my main program I have this line of code:
IMWSResponse response = null;
with response being later used to store the information that amazon sends back after a method call is invoked. But what is the meaning behind setting a variable of an interface type to null?
Also, a interface can implement another interface? It isn't only classes that can implement interfaces, but interfaces themselves as well?
Pproperties can be present in interfaces since properties are actually methods - the use of T GetSomeValue() alongside void SetSomeValue(T value) became so common in other languages, that C# implements these as properties.
The meaning behind setting an interface member to null is the same as setting anyother property to null - since a property's set accessor is a method, it's like calling any other method on the interface. What null means where is up to the implementation.
Interfaces do not implement each other, since and interface cannot contain code and therefore is not implementing; Interface inheritance allows one to require one interface in another. A big example is IEnumerable<T>, which is so closely tied to IEnumerable that it inherits, thus meaning any class implementing IEnumerable<T> must also implement IEnumerable.
An interface is like a contractual agreement. By inheriting an interface from a class, you are saying, "I agree to implement all of the methods defined in this interface". So if you have an interface like this:
public interface IWorker {
void DoWork();
}
and you use that interface like this:
public class Employee : IWorker
{
// you are forced to implement this method
void DoWork {}
}
public class Contractor: IWorker
{
// you are forced to implement this method
void DoWork {}
}
By "inheriting" interfaces by other interfaces, you are simply agreeing to implement any methods in the other interfaces, like so (from MSDN):
interface IBase
{
void F();
}
interface IDerived: IBase
{
void G();
}
class C: IDerived
{
void IBase.F() {...}
void IDerived.G() {...}
}
class D: C, IDerived
{
public void F() {...}
public void G() {...}
}
You do not have to set a variable of an interface type to null, though you have the power to do so. The great thing about interfaces is that you are able to set a variable of the type of interface, to anything that "inherits" that interface.

Use base classes implementation with correct access modifiers

I would like to have an interface for a problem called IProblem. With two methods: Solve() and CheckArguments(). The Problem class will implement the CheckArguments() function because it will be the same for all the problems. But then I have different types of problems like EasyProblem and HardProblem that have different implementations of Solve() method but the CheckArguments() method always be the same and I always want to use the base class Problem()'s implementation.
I would like to have correct modifiers and I'm a bit confused on which method being defined in which class/interface. Not to mention I also have a test project for both these functions.
I'm not sure if your question is "what to use", but I'd suggest an interface and an abstract class:
public interface IProblem {
void Solve();
void CheckArguments();
}
public abstract class Problem : IProblem {
public abstract void Solve();
public void CheckArguments() {
...
}
}
public class EasyProblem : Problem
{
public override void Solve()
{
....
}
}
This way, check arguments is implemented in the base class, all derived classes implement IProblem and every derived class must implement Solve.
If you leave out the interface and only support classes which derive from Problem, you'll make sure that a given class can't give it's own implementation of CheckArguments().
public abstract class Problem {
public abstract void Solve();
public void CheckArguments() {
...
}
}
public class EasyProblem : Problem
{
public override void Solve()
{
....
}
}
...
static Main(string[] args)
{
List<Problem> problemsToSolve = ...
foreach(var problem in problemsToSolve)
{
problem.CheckArguments();
problem.Solve();
}
}
You can try something like:
public interface ISupportArguments
{
bool CheckArguments();
}
public abstract class AbstractProblem : ISupportArguments
{
public bool CheckArguments() {
return true;
}
public abstract void SolveProblem();
}
so every your class derives from AbstractProblem and override it's own version of
SolveProblem(..)
The class structure has been shown by Matten very well.
As regards access modifiers: I'd propose a defensive approach, so that you use the most restrictive access modifier that solves the problem. It is easier to be less restrictive afterwards than to be more restrictive as you might have to explain to some users of your code why they cannot use it anymore.
So for the types (interface and classes): if you don't need them in other assemblies, rather define them as internal. If you want to access the types from your test project, you can use the InternalsVisibleTo attribute to be able to access them from specific assemblies. You add the attribute to the assembly containing the types and provide the name (and for strong named assemblies some additional data) of the test assembly as a parameter.
The same applies to the members. You can also think about implementing the interface explicitly, so you can access the methods only if you access the class via the interface.

Interface in c# issue

I am new in c# development. I just trying to study the interface feature. Based on the articles and notes I read about interfaces, I tried to write a sample code to implement interface based on what I understood from those notes and articles.
But when I debugging the project I got a build error
"Inconsistent accessibility: parameter type 'StartMachine' is less accessible than method 'SwitchBoard.switchPress(StartMachine)'".
What is the problem here ?. or Did I implemented the interface in correct way ? or Is my concept about interface is wrong ?..
Please help.
Thanks in advance.
I posted my code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StartMachine s1 = new Machine1();
SwitchBoard switch1 = new SwitchBoard();
switch1.switchPress(s1);
}
}
interface StartMachine
{
void startMachine();
}
public class Machine1 : StartMachine
{
public void startMachine()
{
HttpContext.Current.Response.Write("Machine 1 Started");
}
}
public class Machine2 : StartMachine
{
public void startMachine()
{
HttpContext.Current.Response.Write("Machine 2 Started");
}
}
public class SwitchBoard
{
public void switchPress(StartMachine switchNum)
{
switchNum.startMachine();
}
}
You need to put a public access modifier in front of your interface. The Machine1/2 classes are public, but your interface is defaulting to internal. This is less accessible than public.
Set interface to public access modifer:
public interface StartMachine {...}
Alternatively, you could change your classes to be:
internal class Machine1: StartMachine {...}
internal class Machine2: StartMachine {...}
For more information on access modifiers, take a look on MSDN.
Correction::
The Switchboard class and switchPress method are public. However, the switchPress method is attempting to access the StartMachine.startMachine (ugh, ambigious naming) method, which is internal (by default). You need to either change the StartMachine interface to be public, or change Switchboard/switchPress tointernal.
Consider the error message, you have an "inconsistent accessibility" between your method and your interface. The fix is simple, mark your interface public.
public interface StartMachine
You have a public method that accepts a StartMachine, yet the interface itself was not marked public. External code would be able to see the method yet not be able to provide the appropriate argument to it.
Make your interface public.
public interface StartMachine
{
...
}
As others have said, mark the interface public. I'll add that I think the confusion here is that while all interface members are automatically public, the interface itself does not have to be. You can have private interfaces for use only internally to a library.

Compiler says I am not implementing my interface, but I am?

Okay, I have two namespaces. One contains my interface and one contains the implementing class. Like this:
namespace Project.DataAccess.Interfaces
{
public interface IAccount
{
string SomeMethod();
}
}
namespace Project.DataAccess.Concrete
{
class Account : Project.DataAccess.Interfaces.IAccount
{
string SomeMethod()
{
return "Test";
}
}
}
With this code I get an error:
'Project.DataAccess.Concrete.Account' does not implement interface member 'Project.DataAccess.Interfaces.IAccount.SomeMethod'. 'Project.DataAccess.Concrete.Account.SomeMethod' cannot implement an interface member because it is not public
If I make the class and method public it works fine. But if I instead qualify the method name with the interface name, that fixes it too. Why? Ex:
namespace Project.DataAccess.Concrete
{
class Account : Project.DataAccess.Interfaces.IAccount
{
string IAccount.SomeMethod()
{
return "Test";
}
}
}
Why does this fix it? And why does it have to be public if I don't do that?
To be clear
I am well aware that making it public fixes it. Making the method signature look like this WITHOUT making anything public fixes it:
string IAccount.SomeMethod()
Why?
Interface implementations need to be public or explicit:
Public:
class Account : IAccount
{
public string SomeMethod()
{
return "Test";
}
}
Explicit:
class Account : IAccount
{
string IAccount.SomeMethod()
{
return "Test";
}
}
The default access modifier in C# is private if you do not specify the access modifier.
You have 2 basic options when implementing intefaces: implicit or explicit. Implicit implementation takes on the form of a public method or property, while explicit is in the form of a method or property prefaced with the IFoo. modifier that is otherwise not public.
interface IFoo
{
void Bar();
}
class FooA : IFoo
{
public void Bar() { }
}
class FooB : IFoo
{
void IFoo.Bar() { }
}
The difference here is that in the case of FooA, void Bar is part of the publicly visible API of the class. Code can call Bar via the instance of the class.
FooA foo = new FooA();
foo.Bar(); // legal
In the case of FooB, void Bar is not part of the publicly visible API of the class. The method can still be called, but it must explicitly be called via the interface.
FooB foo = new FooB();
foo.Bar(); // not legal
IFoo myFoo = foo;
myFoo.Bar(); // legal
Your code does not compile because it walks in the uncharted waters between an implicit and explicit interface implementation. You saw that with your change, you had legally defined an explicit implementation, which is why that particular version compiles. Otherwise, you've also found that the public modifer is needed to make the non-explicit version compile.
Methods implementing interface needs to be public. In your later case, you are declaring it explicitly. This is what specification says about explicit interface implementation.
Explicit interface member
implementations have different
accessibility characteristics than
other members. Because explicit
interface member implementations are
never accessible through their fully
qualified name in a method invocation
or a property access, they are in a
sense private. However, since they can
be accessed through an interface
instance, they are in a sense also
public.
'Project.DataAccess.Concrete.Account.SomeMethod' cannot implement an interface member because it is not public
namespace Project.DataAccess.Concrete
{
public class Account : IAccount
{
public string IAccount.SomeMethod()
{
return "Test";
}
}
}
You're not mentioning in your class declaration that you'll be implementing IAccount.
Your class declaration should look like this:
class Account : IAccount
{
//Implementation here.
}
Also, what's happening is that you're using the "default" protection level for Account, and that protection level isn't "public", but an Interface (IAccount) defines public methods by default.
So, when you preface both the Class and Method names with public you're actually implementing the interface. Likewise, when you declare SomeMethod as
IAccount.SomeMethod()
{
//Implementation Here
}
what you're doing is Explicitly Implementing the interface.
I think declaring it explicitly with string IAccount.SomeMethod() works because .NET knows that this implementation of the method can only be accessed through the interface, and so it carries over the public visibility from the interface. In other words, since you are explicitly saying it is an interface member, the compiler can imply that it has to be public, so you don't have to re-state the obvious.
This is also discussed here: http://msdn.microsoft.com/en-us/library/aa664591%28v=vs.71%29.aspx
It is a compile-time error for an
explicit interface member
implementation to include access
modifiers, and it is a compile-time
error to include the modifiers
abstract, virtual, override, or
static.
Explicit interface member
implementations have different
accessibility characteristics than
other members. Because explicit
interface member implementations are
never accessible through their fully
qualified name in a method invocation
or a property access, they are in a
sense private. However, since they can
be accessed through an interface
instance, they are in a sense also
public.
class Account : IAccount
{
public string SomeMethod()
{
return "Test";
}
}
Tell your class to implement the interface. Using the Interface.Method name explicitly implements the method (but i'm not sure why or how) and you need to make them public.
You want to use Interface.Method to explicitly implement an interface requirement when the class already has a member of the same name
class MyClass : IAccount
{
public int SomeMethod() {}
public string IAccount.SomeMethod() {}
}

Categories