#435 – Implementing an Interface

An interface is a list of class members that a class must implement if it chooses to implement the interface.

Assumed that we have the following IMoo interface.

    interface IMoo
    {
        // Methods
        void Moo();

        // Properties
        List<string> MooLog { get; set; }

        // Events
        event EventHandler<MooEventArgs> CowMooed;
    }

A class implements an interface by first listing the interface in the class declaration, as if it was inheriting from the interface.  It then provides implementations for all of the interface’s members.

    public class Cow : IMoo
    {
        //-- IMoo implementation --
        public void Moo()
        {
            string moo = "Moo !";
            Console.WriteLine("{0}: {1}", CowName, moo);
            MooLog.Add(moo);
            OnCowMooed(moo);
        }

        public List<string> MooLog { get; set; }

        public event EventHandler<MooEventArgs> CowMooed = delegate { };

        protected virtual void OnCowMooed(string mooPhrase)
        {
            CowMooed(this, new MooEventArgs(CowName, mooPhrase));
        }
        //-- IMoo implementation --

        public string CowName { get; set; }
    }
Advertisements