Logo 
Search:

C# FAQ

Submit Interview FAQ
Home » Interview FAQ » C#RSS Feeds

How can I check the type of an object at runtime?

  Shared By: Orville Rodriguez    Date: Feb 06    Category: C#    Views: 1128

Answer:

You can use the is keyword. For example:

using System;

class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;

Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
}

static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:

fred is not an integer
10 is an integer

Share: 
 

Didn't find what you were looking for? Find more on How can I check the type of an object at runtime? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: