Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an object is of a certain type at runtime in C#?

Tags:

c#

types

object

How can I check if an object is of a certain type at runtime in C#?

like image 972
carlfilips Avatar asked Aug 03 '10 23:08

carlfilips


2 Answers

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
like image 85
carlfilips Avatar answered Sep 20 '22 02:09

carlfilips


MyType myObjectType = argument as MyType;

if(myObjectType != null)
{
   // this is the type
}
else
{
   // nope
}

null-check included

Edit: mistake correction

like image 27
Lukasz Madon Avatar answered Sep 23 '22 02:09

Lukasz Madon