Wednesday, March 15, 2017

How to use interfaces in C#.NET

Following is a simple interface with just a one method declaration.

public interface IRobot
    bool ValidateRobot(string robotId);

Now you can write a class and then inherit it from the interface. This class needs to implement the interface. At this point we write the actual implementation of the method declared in the interface.

public class RobotProvider : IRobot
    public bool ValidateRobot(string robotId)
        return robotId == "CorrectRobot" ? true : false;

Finally, we can call the interface method in our main programme.

    static void Main(string[] args)
        IRobot robot = new RobotProvider();
        bool robotResult = robot.ValidateRobot("CorrectRobot");

No comments:
Write comments
Recommended Posts × +