How can I check if an object is of a certain type at runtime in C#?
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
MyType myObjectType = argument as MyType;
if(myObjectType != null)
{
// this is the type
}
else
{
// nope
}
null-check included
Edit: mistake correction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With