C#: The is Keyword

This entry is part 56 of 71 in the series C#

The is keyword can be used to test if an object is of a specified type.
It is normally used in an if statement and its syntax is.

if (object is type)

The object is type expression will return a Boolean expression such as true if it evaluates to true.

In the example below, tiger is a derived class of Animal. We can test it using

if (tiger is Animal)

Note also how the array is tested in line 28.

Is Type
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IsType
{
    class Program
    {
        public class Animal
        { }

        public class Tiger : Animal
        { }

        static void Main()
        {
            string s = "hello";

            if (s is System.String)
            {
                Console.WriteLine("s is a string");
            }

            string[] string_array = { "hello", "why" };

            if (string_array is System.String[])
            {
                Console.WriteLine("string_array is a string array");
            }

            int number = 123456;

            if (number is int)
            {
                Console.WriteLine("number is Integer");
            }

            Animal animal = new Animal();

            if (animal is Animal)
            {
                Console.WriteLine("animal is of type Animal");
            }

            Tiger tiger = new Tiger();

            if (tiger is Animal)
            {
                Console.WriteLine("tiger is of type Animal");
            }

            Console.ReadKey();
        }
    }
}
Series Navigation<< C#: Accessing base class’ hidden members
C#: Virtual method >>
Posted in

Leave a comment

Leave a Reply