#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: