Ian H. Ian H. - 1 year ago 52
C# Question

C# - Creating a saveable object

I want to create a class library, that contains an interface that objects can derive of, lets say


Now, this interface should implement the following functionality:

  • Objects that derive off this interface should have a method
    (similar to the

  • And it should contain a specific constructor, which takes an array of objects as its parameter.

The connection between these two should be that the
method returns a string that takes all the properties that are needed for the
and convert it into a readable string and return it.

Am I going in the correct direction by wanting to use an interface or is an abstract class better suited for this case?

Sadly, interfaces cannot implement constructors, so is there another way to accomplish my goal?

Answer Source

Use an abstract base class that inherits from your intended interface. What you want is more of an implementation detail which is more than what an interface can provide.

public interface ISaveableObject {
    string ToSaveableObject();

abstract base class coould look like this

public abstract class SaveableObject : ISaveableObject {
    protected object[] parameters = new object[0];

    private SaveableObjectBase() { }

    protected SaveableObjectBase(object[] objects) {
        this.parameters = objects;

    public abstract string ToSaveableObject();

So now derived classes have to implement the ToSaveableObject() method and will have access to the objects passed in the constructor to generate the string.

If the construction algorithm for the ToSaveableObject method is the same for all derived types then you should just implement that method in the base abstract class so that all derived classes will have the functionality already built in.