carlfilips
carlfilips

Reputation: 2620

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

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

Upvotes: 8

Views: 12698

Answers (9)

Rm558
Rm558

Reputation: 4994

you can also use switch/case in c# 7 (pattern matching).

string DoubleMe(Object o)
{
    switch (o)
    {
        case String s:
            return s + s;
        case Int32 i:
            return (i + i).ToString();
        default:
            return "type which cannot double.";
    }
}

void Main()
{
    var s= "Abc";
    var i= 123;
    var now = DateTime.Now;

    DoubleMe(s).Dump();
    DoubleMe(i).Dump();
    DoubleMe(now).Dump();
}

enter image description here

Upvotes: 0

Chris O
Chris O

Reputation: 5037

Use the typeof keyword:

System.Type type = typeof(int);

Upvotes: -2

Lukasz Madon
Lukasz Madon

Reputation: 14994

MyType myObjectType = argument as MyType;

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

null-check included

Edit: mistake correction

Upvotes: 4

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59101

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.

Upvotes: 3

Manfred
Manfred

Reputation: 5656

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);
      }
   }
}

Upvotes: 1

duesouth
duesouth

Reputation: 75

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.

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 99957

obj.GetType() returns the type

Upvotes: 1

kbrimington
kbrimington

Reputation: 25642

myobject.GetType()

Upvotes: 1

carlfilips
carlfilips

Reputation: 2620

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

Upvotes: 10

Related Questions