CSharp examples for Reflection:Type
Test an Object's Type
using System;//from ww w . j a va2s . c om using System.IO; class MainClass { public static bool IsType(object obj, string type) { Type t = Type.GetType(type, true, true); return t == obj.GetType() || obj.GetType().IsSubclassOf(t); } public static void Main() { Object someObject = new StringReader("This is a StringReader"); if (typeof(StringReader) == someObject.GetType()) { Console.WriteLine("typeof: someObject is a StringReader"); } if (someObject is TextReader) { Console.WriteLine("is: someObject is a TextReader or a derived class"); } if (IsType(someObject, "System.IO.TextReader")) { Console.WriteLine("GetType: someObject is a TextReader"); } StringReader reader = someObject as StringReader; if (reader != null) { Console.WriteLine("as: someObject is a StringReader"); } } }