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

How to check if an object has a certain type at runtime in C #?

+4
source share
9 answers

You can use the keyword . For instance:

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

outputs the result:

 fred is not an integer 10 is an integer 
+5
source
 MyType myObjectType = argument as MyType; if(myObjectType != null) { // this is the type } else { // nope } 

null check enabled

Edit: error correction

+4
source

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

Method Object.GetType ().

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.

+2
source
 myobject.GetType() 
+1
source

obj.GetType() returns a type

+1
source

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

An expression expresses true if the provided expression is non-zero, and the provided object can be a provided type without throwing an exception.

This is not the same as type checking with GetType.

+1
source

Depending on your use case, "is" will not work properly. Take the Foo class derived from the Bar class. Create an obj object of type Foo. Both "obj - Foo" and "obj is Bar" will return true. However, if you use GetType () and compare with typeof (Foo) and typeof (Bar), the result will be different.

The explanation here and here is a snippet 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); } } } 
+1
source

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

0
source

Use the typeof keyword:

 System.Type type = typeof(int); 
-1
source

All Articles