Search code examples
c#oopinterfaceencapsulation

Understanding Interfaces C#


Been reading all day on interfaces and abstract classes trying to get a grasp on them to better understand the amazon library I'm working with. I have this code:

using MWSClientCsRuntime;

namespace MarketplaceWebServiceOrders.Model
{
    public interface IMWSResponse : IMwsObject
    {
        ResponseHeaderMetadata ResponseHeaderMetadata { get; set; }
    }

and

namespace MWSClientCsRuntime
{
    public interface IMwsObject
    {
        void ReadFragmentFrom(IMwsReader r);
        string ToXML();
        string ToXMLFragment();
        void WriteFragmentTo(IMwsWriter w);
        void WriteTo(IMwsWriter w);
    }
}

My first questions is I thought Interfaces cannot contain fields, however they can contain properties usch as ResponseHeaderMetadata?

Second, in my main program I have this line of code:

IMWSResponse response = null;

with response being later used to store the information that amazon sends back after a method call is invoked. But what is the meaning behind setting a variable of an interface type to null?

Also, a interface can implement another interface? It isn't only classes that can implement interfaces, but interfaces themselves as well?


Solution

  • Pproperties can be present in interfaces since properties are actually methods - the use of T GetSomeValue() alongside void SetSomeValue(T value) became so common in other languages, that C# implements these as properties.

    The meaning behind setting an interface member to null is the same as setting anyother property to null - since a property's set accessor is a method, it's like calling any other method on the interface. What null means where is up to the implementation.

    Interfaces do not implement each other, since and interface cannot contain code and therefore is not implementing; Interface inheritance allows one to require one interface in another. A big example is IEnumerable<T>, which is so closely tied to IEnumerable that it inherits, thus meaning any class implementing IEnumerable<T> must also implement IEnumerable.