Check Type of Object at Runtime in C#
If You want to check the TYPE of an object at runtime in C#
then you have to use IS Keyword
example :
using System;
class CApp
{
public static void Main()
{
string s = "Shubhank";
long i = 900;
Console.WriteLine( "{0} is {1}an integer", s, (IsIntegerType(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsIntegerType(i) ? "" : "not ") );
}
static bool IsIntegerType( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
Output will be
Shubhank is not an integer
900 is an integer
then you have to use IS Keyword
example :
using System;
class CApp
{
public static void Main()
{
string s = "Shubhank";
long i = 900;
Console.WriteLine( "{0} is {1}an integer", s, (IsIntegerType(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsIntegerType(i) ? "" : "not ") );
}
static bool IsIntegerType( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
Output will be
Shubhank is not an integer
900 is an integer
Comments
Post a Comment