tags:

views:

148

answers:

8

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

Thanks in advance.

+5  A: 

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
carlfilips
I find the is keyword way underused. It is so much easier to read!
Russell
This works. Thanks for your answer.
carlfilips
Using `is` usually means two casts when one would have sufficed. Which is why it's not used often. Granted, the performance hit is probably imperceptible 99.99% of the time.
Matt Greer
Depending on the requirements either `is' or `GetType()' might be the right solution. See my answer for details about the difference including code.
John
+1  A: 
myobject.GetType()
kbrimington
+1  A: 

obj.GetType() returns the type

Mark Cidade
May want to add a `null` check to promote good practice.
ChaosPandion
I'm not sure I ever saw an object in .NET without a type in the past ten years... - So in this case I'd go without the check for null for efficiency.
John
He means: `object obj = null; obj.GetType();`, that will throw a NullReferenceException
Matt Greer
A: 

Use the typeof keyword.

Chris O
+3  A: 
MyType myObjectType = argument as MyType;

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

null-check included

Edit: mistake correction

lukas
You need to store the result of the cast in something.`MyType myType = myObject as MyType;`, then check to see if `myType` is null; and this doesn't mean `myObject` is a `MyType`, it just means it is assignable to that. Which is an important difference.
Matt Greer
+1  A: 

I can't add comments so I'll have to add this as an answer. Bear in mind that, from the documentation (http://msdn.microsoft.com/en-us/library/scekt9xw%28VS.80%29.aspx):

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

This not the same thing as checking the type with GetType.

A: 

Depending of your use case 'is' will not work as expected. Take a class Foo derived from class Bar. Create an object obj of type Foo. Both 'obj is Foo' and 'obj is Bar' will return true. However, if you use GetType() and compare against typeof(Foo) and typeof(Bar) the result will be different.

The explanation is here and here is a piece of source code demonstrating this difference:

using System;

namespace ConsoleApp {
   public class Bar {
   }

   public class Foo : Bar {
   }

   class Program {
      static void Main(string[] args) {
         var obj = new Foo();

         var isBoth = obj is Bar && obj is Foo;

         var isNotBoth = obj.GetType().Equals(typeof(Bar)) && obj.GetType().Equals(typeof(Foo));

         Console.Out.WriteLine("Using 'is': " + isBoth);
         Console.Out.WriteLine("Using 'GetType()': " + isNotBoth);
      }
   }
}
John
A: 

The type information operators (as, is, typeof): http://msdn.microsoft.com/en-us/library/6a71f45d(VS.71).aspx

The Object.GetType() method.

Keep in mind that you may have to deal with inheritance hierarchies. If you have a check like obj.GetType() == typeof(MyClass), this may fail if obj is something derived from MyClass.

Merlyn Morgan-Graham