Mega Code Archive

 
Categories / C# / Reflection
 

Use Type GetType to check the type of an object

using System; 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 (IsType(someObject, "System.IO.TextReader"))         {             Console.WriteLine("GetType: someObject is a TextReader");         }     } }