9.1 Rules

Rules within C# that must be followed when it comes to interfaces

  1. An interface can only define the properties and method signatures. It does not do any implementation. We define what properties and methods the class should follow.

  2. Classes inherited from interfaces must honor the property and method signatures. They are promises between the two saying that they will have what the interface wants.

  3. Many classes can inherit from a particular interface.

  4. An interface may inherit from multiple base interfaces.

  5. A class may implement-inherit from multiple interfaces.

  6. A C# class may only inherit from one class.

Example

 interface IHuman
 {
    void Read();
    void Write(object obj);
    int Height { get; set; }
    int Weight { get; set; }
 }

 public class Human : IHuman
 {
    private int height;
    private int weight;
    public Human(string s)
        {
            MessageBox.Show(s);     
        }
        // implement the Read method
        public void Read()
        {
            MessageBox.Show(
                “Implementing the Read Method for IHuman”);
        }
        // implement the Write method
        public void Write(object o)
        {
            MessageBox.Show(
                “Implementing the Write Method for IHuman”);
        }
        // implement the property Height
        public int Height
        {
            get { return height; }
            set { height = value; }
        }
// implement the property Weight
        public int Weight
        {
            get { return weight; }
            set { weight = value; }
        }
}

Discussion

If you have written out this code in Visual Studio, try commenting out one of the methods or properties by typing // in front of the lines. You should get an error from visual studio saying you have not fulfilled all the promises of the interface.

Next: Code Intent

Last updated