C# Interfaces – Implementing Interface Properties

cinterfacesobject-orientedproperties

As the code below, class Foo1 implements interface IFoo, which has a property of IData.

public interface IFoo
{
    public IData Data { get; set; }
}

public interface IData { ... }

public class DataA : IData {...}
public class DataB : IData {...}

public class Foo1 : IFoo
{
    private DataB _data;
    public IData Data
    {
        get { return _data; }
        set { _data = new DataB(value); }
    }
}

If the user assigns the Data property of Foo1 with an object of DataA, and then gets the property value back later. He will get an object of DataB instead of DataA. Does this violate any OO principles? Thanks.

Best Answer

No, you are not violating any OO principles. Least of all because properties are not an OO concept.

There is also no rule that states that you must be able to retrieve from a property exactly the value that you stored in it.

Without better names or more documentation, you might be violating the "principle of least astonishment" but that is hard to tell from such a contrived example. And it is not an OO principle, but a general programming one.

Related Topic