Using the is and as Keywords with Classes-Class Conversions - CSharp Custom Type

CSharp examples for Custom Type:is

Introduction

Using the is Keyword

To do a comparison to see whether an object is of a certain type, use the is keyword.

You use the is keyword to determine whether a variable is of a specified type.

The format for using this keyword is as follows:

(expression is type)

Demo Code

using System;// ww w.j  a va2 s.  co m
class Person
{
    protected string Name;
    public Person() { }
    public Person(string n) { Name = n; }
    public virtual void displayFullName()
    {
        Console.WriteLine("Name: {0}", Name);
    }
}
class Employee : Person
{
    public Employee() : base() { }
    public Employee(string n) : base(n) { }
    public override void displayFullName()
    {
        Console.WriteLine("Employee: {0}", Name);
    }
}
class IsApp
{
    public static void Main()
    {
        Person pers = new Person();
        Object emp = new Employee();
        string str = "String";
        if (pers is Person)
            Console.WriteLine("pers is a Person");
        else
            Console.WriteLine("pers is NOT a Person");
        if (pers is Object)
            Console.WriteLine("pers is an Object");
        else
            Console.WriteLine("pers is NOT an Object");
        if (pers is Employee)
            Console.WriteLine("pers is an Employee");
        else
            Console.WriteLine("pers is NOT an Employee");
        if (emp is Person)
            Console.WriteLine("emp is a Person");
        else
            Console.WriteLine("emp is NOT a Person");
        if (str is Person)
            Console.WriteLine("str is a Person");
        else
            Console.WriteLine("str is NOT a Person");
    }
}

Related Tutorials