Using the is Keyword to Work with an Interface : is « Language Basics « C# / C Sharp






Using the is Keyword to Work with an Interface

 


using System;
   
public interface IPrintMessage
{
    void Print();
};
   
class Class1
{
    public void Print()
    {
        Console.WriteLine("Hello from Class1!");
    }
}
   
class Class2 : IPrintMessage
{
    public void Print()
    {
        Console.WriteLine("Hello from Class2!");
    }
}
   
class MainClass
{
    public static void Main()
    {
        PrintClass   PrintObject = new PrintClass();
   
        PrintObject.PrintMessages();
    }
}
   
class PrintClass
{
    public void PrintMessages()
    {
        Class1      Object1 = new Class1();
        Class2      Object2 = new Class2();
   
        PrintMessageFromObject(Object1);
        PrintMessageFromObject(Object2);
    }
   
    private void PrintMessageFromObject(object obj)
    {
        if(obj is IPrintMessage)
        {
            IPrintMessage PrintMessage;
   
            PrintMessage = (IPrintMessage)obj;
            PrintMessage.Print();
        }
    }
}

 








Related examples in the same category

1.is Checker
2.The is operator confirms that the employee is a manager.
3.choose between two overloaded methods at run-time using the 'is' keyword