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#?
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
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.
myobject.GetType()
obj.GetType()
returns the type
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.
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);
}
}
}
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();
}
Use the typeof keyword:
System.Type type = typeof(int);
精彩评论