Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an interface to a partial class

Tags:

c#

interface

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?

like image 655
Ian Vink Avatar asked Dec 11 '13 00:12

Ian Vink


People also ask

Can a partial class implement an interface?

Partial class, interface and structure was introduced in C# 2.0. Now it is possible to split the definition of an class, interface and structure over more than one source files. Moreover the other parts of the class, struct, or interface should be defined in the same namespace or assembly.

Can we implement interface partially in C#?

In C#, you can split the implementation of an interface into multiple files using the partial keyword. The partial keyword indicates that other parts of the interface can be defined anywhere in the namespace. All the parts must use the partial keyword and must be available at compile time to form the final type.

Can different parts of a partial class inherit from different interfaces?

All the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations.


2 Answers

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.

like image 67
MarcinJuraszek Avatar answered Nov 15 '22 16:11

MarcinJuraszek


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.
like image 35
Eric Eskildsen Avatar answered Nov 15 '22 14:11

Eric Eskildsen