#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

#434 – Interfaces

An interface is a list of methods, properties, events and indexers that a class may implement.  The declaration of an interface looks similar to a class declaration, but doesn’t contain an implementation for any of its members.

        public interface ICowHerd
        {
            // Properties
            string HerdName { get; set; }
            string HerdMotto { get; set; }
            List<CowInfo> Cows { get; set; }

            // Methods
            void DisplayHerdInfo();
            void DisplayCowInfo(int cowIndex);

            // Events
            event EventHandler<CowAddedEventArgs> CowAdded;
        }

You can’t do anything with an interface by itself. You can’t instantiate it like a class.  Instead, a class can choose to implement an interface, which means that it will define an implementation for every member of the interface.  You can think of the interface as a contract that dictates the exact members that a class must implement if it decides to implement the interface.