Ian Vink
Ian Vink

Reputation: 68770

Adding an interface to a partial class

I have a class that is generated by a third party tool:

public partial class CloudDataContext : DbContext 
{
    // ...SNIPPED... 
    public DbSet<User> Users { get; set; } 

}

I create a partial class and then assign an interface so that I can inject this class later:

public partial class CloudDataContext : IDataContext
{

}   

The IDataContext has the single property Users.

This won't compile, the compiler complains that the interface isn't implemented.

If I move the interface to the generated class, it works fine. I can't do that though as it's generated code.

How can I apply an interface to a partial class to expose the class as defined above?

Upvotes: 18

Views: 20866

Answers (5)

Greg Z.
Greg Z.

Reputation: 1566

Make sure that all files of the partial class have "C# compiler" Build Action in VS.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

The problem must be somewhere else, because you can implement interface in the other part of partial class than it's set on. I just tried following and it compiles just fine:

public interface IFoo
{
    int Bar { get; set; }
}

public partial class Foo
{
    public int Bar { get; set; }
}

public partial class Foo : IFoo
{

}

The properties probably use different types in interface and class.

Upvotes: 34

Per
Per

Reputation: 201

In my case, the interface method signature didn't mention a value (uint direction) that the actual method expected. This showed up as the interface having errors in one of the partial classes. Make sure that the interface for a method is actually the same as the method signature itself. D'oh.

Upvotes: 0

Veacelsav Dragancea
Veacelsav Dragancea

Reputation: 21

IN my Case problem was that interface Method that was implemented in other part of the partial class was not compiling and C# was giving error of not implemented Method

Upvotes: 1

Eric Eskildsen
Eric Eskildsen

Reputation: 4759

Here's a quick checklist. Do the classes have identical:

  • Names?
  • Namespaces?
  • Access modifiers?

Example:

  • You decide to split an existing class into two files.
  • The original file's namespace doesn't match its folder path.
  • Consequently, the new class file you create has a mismatching namespace.
  • Build fails.

Upvotes: 5

Related Questions