Jed Jed - 4 days ago 5
C# Question

How to force multiple Interfaces to include the same properties?

I am trying to figure out a way to force all of my Interfaces to include properties of the same name/type.

For example: I have two Interfaces; IGetAlarms and IGetDiagnostics. Each of the Interfaces will contain properties that are specific to the Interface itself, however I want to force the two Interfaces (and all other Interfaces that may be added later) to include properties of the same name. So, the result may look something like the this:

interface IGetAlarms
{
string GetAlarms();
DateTime LastRuntime { get; set; }
}

interface IGetDiagnostics
{
string GetDiagnostics();
DateTime LastRuntime { get; set; }
}


Notice that both Interfaces include a DateTime property named LastRuntime.

I would like to know if there is some way I can force other Interfaces that will be added later to include the DateTime LastRuntime property. I have naively attempted to have all my Interfaces implement another Interface (IService) - which includes the LastRuntime property. However, that doesn't solve my problem as that simply forces the class to implement the property - not all the Interfaces.

Thanks.

Answer

An interface can inherit from other interfaces.

interface IDerived : IBase
{
    string Foo { get; set; }
}

interface IBase
{
    DateTime LastRunDate { get; set; }
}

Any class deriving from IDerived will have to implement the methods/properties of IBase as well.

class Derived : IDerived 
{
    #region IDerived Members

    public string Foo { get; set; }

    #endregion

    #region IBase Members

    public DateTime LastRunDate {get;set;}

    #endregion
}
Comments