9

I have a question regarding a problem with L2S, Autogenerated DataContext and the use of Partial Classes. I have abstracted my datacontext and for every table I use, I'm implementing a class with an interface. In the code below you can see I have the Interface and two partial classes. The first class is just there to make sure the class in the auto-generated datacontext inherets Interface. The other autogenerated class makes sure the method from Interface is implemented.

namespace PartialProject.objects
{

public interface Interface
{
    Interface Instance { get; }
}

//To make sure the autogenerated code inherits Interface
public partial class Class : Interface { }

//This is autogenerated
public partial class Class
{
    public Class Instance
    {
        get
        {
            return this.Instance;
        }
    }
}

}

Now my problem is that the method implemented in the autogenerated class gives the following error: -> Property 'Instance' cannot implement property from interface 'PartialProject.objects.Interface'. Type should be 'PartialProjects.objects.Interface'. <-

Any idea how this error can be resolved? Keep in mind that I can't edit anything in the autogenerated code.

Thanks in advance!

Bas
  • 1,232
  • 1
  • 12
  • 26

2 Answers2

12

You can solve this by implementing the interface explicitly:

namespace PartialProject.objects
{
  public interface Interface
  {
    Interface Instance { get; }
  }

  //To make sure the autogenerated code inherits Interface
  public partial class Class : Interface 
  {
    Interface Interface.Instance 
    {
      get
      {
        return Instance;
      }
    }
  }

  //This is autogenerated
  public partial class Class
  {
     public Class Instance
     {
        get
        {
          return this.Instance;
        }
     }
  }
}
Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
JJoos
  • 587
  • 1
  • 6
  • 17
  • 1
    Voted. Thank you for nice solution. I've almost "cracked" my head trying to make a work-around for limitations imposed by interfaces. – Igor Soloydenko Aug 15 '11 at 19:09
  • Just in case anyone runs into the following error after implementing the above solution look [here](http://stackoverflow.com/questions/2669031/compilation-error-the-modifier-public-is-not-valid-for-this-item-while-crea): the modifier 'public' is not valid for this item - basically remove any access modifiers as those properties will be forced as private (which makes sense when you think about it). – dyslexicanaboko Jan 28 '13 at 22:32
2

Return types aren't covariant in C#. As you can't change the auto-generated code the only solution I see is to change the interface:

public interface Interface<T>
{
    T Instance { get; }
}

And change your partial class accordingly:

public partial class Class : Interface<Class> { }
helium
  • 1,077
  • 1
  • 9
  • 15