How do I check object type using the is keyword?

Category: System, viewed: 288 time(s).

Using the is keyword we can check if an object is an instance of a specified class. This is expression returns true if the object is an instance of the speficied class or if the object is inherited from the specified class. The is expression returns true if the provided object is non-null, and the specified object can be casted to the specified object type without throwing an exception.

using System;
using System.Collections;

namespace Kodecsharp.Example.System {
    class IsInstanceOfExample {
        public static void Main(string[] args) {
            ArrayList list = new ArrayList();
            list.Add("Hello");
            list.Add(Int32.Parse("10"));
            list.Add(new DateTime());
            list.Add(Double.Parse("10.99"));
            list.Add(true);
            list.Add(new A());
            list.Add(new B());

            for (int i = 0; i < list.Count; i++) {
                Object o = list[i];
                if (o is string) {
                    Console.WriteLine("\"" + (string)o + "\" is a string");
                } else if (o is Int32) {
                    Console.WriteLine("\"" + (Int32)o + "\" is an Int32");
                } else if (o is Double) {
                    Console.WriteLine("\"" + (Double)o + "\" is a Double");
                } else if (o is DateTime) {
                    Console.WriteLine("\"" + (DateTime)o + "\" is a DateTime");
                } else if (o is A) {
                    Console.WriteLine("\"" + o + "\" is an A");
                } else {
                    Console.WriteLine("\"" + o + "\" is a " + o.GetType());
                }
            }

            Console.ReadLine();
        }
    }

    class A {
    }

    class B : A {
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page