C# is operator
Description
The is
operator tests whether an object derives
from a specified class or implements an interface.
It is often used to test before downcasting.
Syntax
is
operator tells if a reference is a certain class.
We can determine whether an object is of a certain type by
using the "is
" operator.
Its general form is shown here:
expr is type
Example
Example for C# is operator
using System;//from w w w. j a v a2 s . com
class Person
{
public string name;
}
class Employee : Person
{
public string companyName;
}
class Program
{
static void Main(string[] args)
{
Person p = new Employee();
Console.WriteLine(p is Employee);
}
}
The output:
Example 2
The following code shows how to use the is Keyword to Work with an Interface.
using System;/*w w w. j a v a 2s . co m*/
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();
}
}
}
The code above generates the following result.
Example 3
Use 'is' to avoid an invalid cast
using System; /*from ww w. j ava2s . c om*/
class A {}
class B : A {}
class CheckCast {
public static void Main() {
A a = new A();
B b = new B();
if(a is B)
b = (B) a;
}
}
The code above generates the following result.
Example 4
The following code show to choose between two overloaded methods at run-time using the 'is' keyword.
using System;//from w ww . j a va2s.c om
public class BankAccount {
virtual public void Withdraw() {
Console.WriteLine("Call to BankAccount.Withdraw()");
}
}
public class SavingsAccount : BankAccount {
override public void Withdraw() {
Console.WriteLine("Call to SavingsAccount.Withdraw()");
}
}
public class MainClass {
public static void Main(string[] strings) {
BankAccount ba = new BankAccount();
Test(ba);
SavingsAccount sa = new SavingsAccount();
Test(sa);
}
public static void Test(BankAccount baArgument) {
if (baArgument is SavingsAccount) {
SavingsAccount saArgument = (SavingsAccount)baArgument;
saArgument.Withdraw();
} else {
baArgument.Withdraw();
}
}
}
The code above generates the following result.