Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
Chev Avatar asked Jun 14 '11 19:06

Chev


People also ask

What happens if a class has implemented an interface but has not provided implementation for that method defined in interface?

So it specifies a set of methods that the class has to implement. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract.

Can I have a class implementing interface methods not implementing interface can I have methods along with interface methods and other new methods also?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

Can interface be used without implementation?

Interface are actually contract definitions, any class implementing the interface abides by the contract. You can implement interface without the key word implements by creating anonymous class.


1 Answers

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.

like image 83
ChrisWue Avatar answered Oct 18 '22 03:10

ChrisWue