Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you implement an interface on a Linq2Sql class?

I have an interface called IAddress, and a class called Address that handles street, city, state/province, postal code and country. I have a couple of Linq2Sql classes that has all the address information and would like to implement the interface IAddress, and pass that in to the constructor for Address that would the load the property values.

Is it possible have a Linq2Sql class impment and interface through the partial class that I created for it? Thanks in advance!

Additional comments

In my class I have a property called MailToStreet, I want that to map to IAddress.Street. Is there a way to do this in the partial class?

Solved

Thanks StackOverflow community! It was a snap! Here is my final code:

public partial class Location : IAddress
{
    string IAddress.Street
    {
        get { return this.Street; }
        set { this.Street = value; }
    }

    string IAddress.City
    {
        get { return this.City; }
        set { this.City = value; }
    }

    string IAddress.StateProvince
    {
        get { return this.StateProvince; }
        set { this.StateProvince = value; }
    }

    string IAddress.PostalCode
    {
        get { return this.PostalCode; }
        set { this.PostalCode = value; }
    }

    string IAddress.Country
    {
        get { return this.Country; }
        set { this.Country = value; }
    }
}
like image 791
mattruma Avatar asked Oct 22 '09 18:10

mattruma


1 Answers

LinqToSQL classes are partial classes, so you can have an additional file that implements the interface for the LinqToSQL class.

Just add this to a new file, using the same class name as your LinqToSQL class:

public partial class LinqToSqlClass : IFoo {
    public void Foo() {
        // implementation
    }
}

If your LinqToSQL class already implements the necessary proporties you should be able to only include the interface declaration.

To answer the comment about using a differently-named LinqToSQL property to implement the interface, you can use the syntax above and just call the LinqToSQL property from the interface property, or to keep things a bit cleaner, use explicit implementation:

public partial class LinqToSqlClass : IFoo {
    void IFoo.Foo() {
        return this.LinqFoo(); // assumes LinqFoo is in the linq to sql mapping
    }
}

By using this syntax, clients accessing your class will not see a redundant property used only for implementing an interface (it will be invisible unless the object is cast to that interface)

like image 66
Ryan Brunner Avatar answered Nov 04 '22 19:11

Ryan Brunner