codeasy .net
or Sign Up
C# Intermediate > 6 One step ahead > Interfaces in C#

I Know Exactly What To Do

I'd lost all interest in the article about machine-to-human binding. I'll come back to it later, I thought. All I could think about now was Commander and Wonderland. What should I do?

"I think your point of view is slightly pessimistic," I heard as Noname entered my thoughts again.
"Why?" I said. "We just discovered that humanity's only hope is imaginary. How could that possibly not sound pessimistic? It's a full-fledged disaster!"
"Well, is it okay if I share my point of view?" Noname asked respectfully.
"Sure, go ahead," I answered.

"Based on what we learned about Commander, humanity has been completely controlled by machines for quite a while, right? Controlled at such a high level that humanity didn't even know about it. That's an accurate summary of yesterday, yes?" Noname asked.
"Right," I agreed, not feeling any better about my predicament at this point.
Noname continued, "And today is the first day that you know about this fact. Now, what does that mean?"

I had to stop and think for a moment. Everything had been happening so fast lately. After a few seconds, I started to realize where Noname was leading me. "They don't know that I know!" I shouted in my head. "The machines have no clue that we know who... or what... Commander is," I shouted.
"Exactly, Teo. Today is the first day that you are one step ahead of the machines. Let's not miss this opportunity."
"Thank you, Noname. Now I know exactly what to do," I exclaimed.
"Happy to help my human friends," he said. "If I may ask, what is your next action?"
"You'll see..."

Codeasy Communication Module

Interfaces

Once I had settled down at a terminal, I pinged Noname again in my head. "Noname, I need you to show me the Commander's communication module. I need to see how it sends and receives commands," I said.
"Got it. Here it is:"

public interface ICommunicationModule
{
    void Send(string message);
    string Receive();
}

public class CommunicationSystem
{
    private ICommunicationModule _communicationModule;

    public CommunicationSystem(ICommunicationModule module)
    {
        _communicationModule = module;
    }

    public void SendMessage(string message)
    {
        Console.WriteLine("Opening communication channel Wonderland");
        _communicationModule.Send(message);
    }

    public string ReceiveMessage()
    {
        Console.WriteLine("Opening communication channel to Wonderland");
        return _communicationModule.Receive();
    }
}

I was pretty sure that modifying this module would help my cause, but I couldn't understand how it worked. "Noname, can you please give me a crash course on interfaces?" I asked. "I've heard about this concept a couple times, but we never covered it in class."
"Sure, it would be a pleasure to explain it to you."

"An interface is an abstraction that indicates what a class that implements it can do. An interface contains functionalities that a class can implement."
"Noname, no matter how hard you try to explain things in simple terms, I can never get it until you show me an example," I said, hoping I didn't come off as sarcastic.
He agreed and sent said example to my terminal:

public interface IClonable
{
    object Clone();
}

"Here you can see an interface IClonable. It declares one method called Clone. This interface tells us 'every class that implements me should have a method Clone.' Are you following?" Noname asked.
"Kind of... How do you use it?" I replied.

public class Car : IClonable
{
    public object Clone() // This method implements method Clone
                          // from the interface
    {
        return new Car();
    }
}

"Here is a class Car that implements IClonable. To properly implement interface IClonable, class Car should have a public method Clone that returns object."
"Ok, got it," I said. "The interface acts as a base class, but instead of implementing methods, it only declares them," I said, reinterpreting Noname's words.

"Exactly, Teo! Now, I should emphasize several constraints and differences between the usage of interfaces and classes. I'll give you some practical assignments to ensure you understand what I mean," Noname replied.
"Sure, but first... Why do all of your interface names start with an I?" I asked.

"This is another name convention in C#. Always start your interface name with a letter 'I'," he replied, "like IConvertable, IClonable, ICat, IDog. Ok - now a few facts about interfaces that you'd better remember."

C Sharp Naming Conventions Flowchart

  1. An interface can contain methods or properties but not fields, constants, or constructors.
    IncorrectCorrect
    public interface IWorker
    {
        string Name;    // No - Fields forbidden
        const int Age;  // No - Constants forbidden
        IWorker();      // No - Constructors forbidden
    }
    
    public interface IWorker
    {
        string Name { get; }
        void DoWork();
    }
    

    Delete from the interface IFactory forbidden members to make the program compile. Don't delete valid members!

  2. A class can inherit from multiple interfaces, but only from one class. To derive from several interfaces, list them separated by a comma, as shown in the next example.

    "Here's a comparison table that shows the difference between derivation from two interfaces and two classes," Noname said. "It is absolutely valid to derive a class or interface from as many interfaces as you want, but you cannot derive from more than one class."

    IncorrectCorrect
    public class Worker
    {
        public virtual void DoWork()
        {
            // Some code
        }
    
        public virtual void PrintResult()
        {
            // Some code
        }
    }
    
    public class Person
    {
        public virtual string GetName()
        {
            // Some code
        }
    }
    
    // Wrong! Con't derive from two classes
    public class HumanWorker : Worker, Person
    {
        // Some code
    }
    public interface IWorker
    {
        void DoWork();
        void PrintResult();
    }
    
    public interface IPerson
    {
        string GetName();
    }
    
    // This is OK: derive from two interfaces
    public class Worker : IWorker, IPerson
    {
        public void DoWork()
        {
            // Some code
        }
    
        public void PrintResult()
        {
            // Some code
        }
    
        public string GetName()
        {
            // Some code
        }
    }
    

    Remove double inheritance from classes by converting classes HouseForSale and Property to interfaces. Add "I" at the beginning of their names to get IHouseForSale and IProperty.

    Remove double inheritance from classes by converting class SoftwareDeveloper to an interface. Add "I" at the beginning of its name to get ISoftwareDeveloper.

  3. If a class implements an interface, it must implement all of its members.

    "Here's another diagram," Noname said. "To the left, you see the code where I forgot to implement a method PrintResult from the interface IWorker; to the right, a fixed version of that code."

    IncorrectCorrect
    public interface IWorker
    {
        void DoWork();
        void PrintResult();
    }
    
    public class Worker : IWorker
    {
        public void DoWork()
        {
            // Do some stuff
        }
    
        // Method PrintResult is not implemented!
        // This will generate a compiler error.
    }
    
    public interface IWorker
    {
        void DoWork();
        void PrintResult();
    }
    
    // Implements both methods from IWorker
    public class Worker : IWorker
    {
        public void DoWork()
        {
            // Do some stuff
        }
    
        public void PrintResult()
        {
            // Print something
        }
    }
    

    Finish the implementation of the interface IBestInTheWorldProgrammer to make the code compile. In the method ReadDocumentation, output to the screen "Sometimes I read the documentation."; in the method WriteCode, output "I adore writing code!"

  4. Interface members are automatically public, and they can't include any access modifiers.
    IncorrectCorrect
    public interface IWorker
    {
        // Wrong. Can't have access modifiers here
        protected string Name { get; }
    
        // Wrong. Can't have access modifiers here
        public void DoWork();
    }
    
    public interface IWorker
    {
        // Right. No access modifier
        string Name { get; }
    
        // Right. No access modifier
        void DoWork();
    }

    Remove access modifiers from an interface to make the code compile.

  5. When a class implements an interface, it must have a public access modifier for all members that implement an interface.

    "Looking at the following comparison table, pay attention to access modifiers for each method and property," Noname said.

    IncorrectCorrect
    public interface IWorker
    {
        string Name { get; }
        void DoWork();
    }
    
    public class Worker : IWorker
    {
        // Doesn't implement interface
        private void DoWork()   // Wrong
        {
        }
    
        // Doesn't implement interface
        protected string Name { get; }  // Wrong
    }
    public interface IWorker
    {
        string Name { get; }
        void DoWork();
    }
    
    public class Worker : IWorker
    {
        // Public method implements interface
        public void DoWork()   // Right
        {
        }
    
        // Public property implements interface
        public string Name { get; }  // Right
    }

    Change access modifiers to make the code compile.

  6. An interface can't have implementation of methods; only declaration.

    "There are no secrets to this rule," Noname explained. "Just don't implement anything in the interface. Leave implementation to a derived class."

    IncorrectCorrect
    public interface IWorker
    {
        // Error! Can't have implementation here!
        string Name { get { return "John"; } }
    
        // Error! Can't have implementation here!
        void DoWork()
        {
            // Some code
        }
    }
    public interface IWorker
    {
        string Name { get; } // Right
    
        void DoWork(); // Right, no implementation
    }
    
    public class Worker : IWorker
    {
        public void DoWork()
        {
            // Implementation of the method
        }
    
        public string Name
        {
            get
            {
                // Implementation of the property
            }
        }
    }

    Remove implementation and all forbidden members from the interface IMessage. Move them to the class Message, so that class Message implements interface IMessage. Your program should compile.

"Thanks, Noname, this is plenty of information about interfaces. Unfortunately, all this information doesn't help that much, because I don't know how to apply it to my cause... If I want to replace an existing implementation with my own, say, on Commander's server, how do I do that?" I asked.
"You need to use polymorphism," he answered.
"Can you tell me about that as well?"
"Sure, so listen..."

Adventure awaits you at Сodeasy

C# Intermediate > 6 One step ahead > Interfaces in C#

This site uses cookies. By continuing to browse this site you are agreeing to our use of cookies.

Got it!