C# is operator
In this chapter you will learn:
- What is IS operator
- Get to know is operator
- Example for C# is operator
- How to use is operator with interface
- Use 'is' to avoid an invalid cast
- Runtime check with in keyword
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;// ww w . j a va2 s . c o m
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 ww.ja v a 2s. c om*/
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; // w w w . j a va 2 s .com
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 w w . ja v a 2s .c o m*/
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.
Next chapter...
What you will learn in the next chapter: