C# FAQ: How check the object type at runtime

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How check the object type at runtime?

How can the type of an object be checked at runtime? The is keyword is used for this purpose. The following is an example of usage for the is keyword:

using System; 
 
class ClassAppl 
{
   static bool isInteger (object o)
   { 
      if (o is int || o is long)
      {
         return true;
      }
      else 
      {
         return false;
      }
   }
 
   public static void Main()
   { 
      string aString = "C#"; 
      long longType = 99; 
 
      Console.WriteLine ("{0} is {1} an integer", aString, 
         (isInteger (aString) ? "" : "not ")); 
      Console.WriteLine ("{0} is {1} an integer", longType, 
         (isInteger (longType) ? "" : "not ")); 
   }
}

generates the output:


 Example output (program output)
C# is not an integer

99 is an integer

See also



Personal tools