is operator
In this chapter you will learn:
- Get to know is operator
- How to use is operator with interface
- Use 'is' to avoid an invalid cast
- Runtime check with in keyword
Using is operator
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
using System;// ja va2 s . c om
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:
is interface
The following code shows how to use the is Keyword to Work with an Interface.
using System;/* j a v a 2 s . com*/
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();
}
}
}
is for invalid casting
using System; //from j a va2s. c o m
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;
}
}
Runtime check with in keyword
The following code show to choose between two overloaded methods at run-time using the 'is' keyword.
using System;//from j a va 2 s. co 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();
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class