Charles Cavalcante
Charles Cavalcante

Reputation: 1618

(un)Inheritance in C#

this is strange but I really need it. I need to inherit a class without inherit their base class but I don't know how.

I have a base abstract entity class from a framework like this:

public abstract class AbstractEntity
{
    public bool Validate(){};
    public List<ValidationErrors> erros;

    // and so many more properties and methods
}

My custom class inherit this abstract base class:

public class Contact : AbstractEntity
{
    public int id
    public string name;
    public string phone;
}

I'm using this class Contact on a webservice and I need only the custom properties, how can I re-use the class Contact without the inheritance AbstractEntity?

I don't want to duplicate this class. Sorry if this sounds stupid.

EDIT

This is a project already created with a code generator, I can't change the classes structures. For this reason I wanted to instantiate that class without the abstract class.

As I can not change it now and need it urgently, I will duplicate this class without the abstraction and use it.

Upvotes: 0

Views: 190

Answers (4)

patmortech
patmortech

Reputation: 10219

While I think that using a simple DTO would probably be the easiest solution, another option would be to implement the IXMLSerializable interface on your Contact class and have it only serialize the properties you care about. Of course, this would affect the XML serialization of the object in other situations as well, not just with the web services.

Upvotes: 0

John Alexiou
John Alexiou

Reputation: 29274

Try containment.

public class NotAnEntity 
{
    public Contact { get; set; }

    public static implicit operator Contact(NotAnEntity other)
    {
        return other.Contact;
    }
}

Upvotes: 0

Nerf42
Nerf42

Reputation: 191

As far as I know you cannot break the inheritance chain. If you want a Contact that doesn't inherit AbstractEntity, you must create a new Contact class that doesn't list AbstractEntity as a parent.

Sorry, that's just how C# is designed.

Upvotes: 1

Chris Shain
Chris Shain

Reputation: 51369

Sounds like you need an interface.

Extract an interface (IAbstractEntity) from AbstractEntity. Or maybe IContact from Contact- the question isn't very clear about which class has the methods and properties that you want to share. It would looks something like this:

public interface IContact
{
    int Id { get; }
    string Name { get; }
    string Phone { get; }
}

Implement IContact on Contact. Then modify any methods that only use the particular methods/properties in IContact to use an IContact instead of Contact.

And I agree with @Jamie-Penney, it sounds like you should read http://en.wikipedia.org/wiki/Data_transfer_object

Finally, if this is a DTO, you are probably going to find yourself in need of something like AutoMapper

Upvotes: 2

Related Questions