C# type examination:
, and typeof
comparison GetType
is
When processing types in C#, there are many ways to check the type of object or variable. Understanding the difference between , and
typeof
GetType
is
The operator is a compilation operator, which returns a object that indicates the specified type. It is usually used to compare the type of object during compilation. For example: typeof
typeof
Type
<code class="language-csharp">Type t = typeof(int); if (t == typeof(int)) // 一些代码</code>
GetType
The operator is a runtime operator. If the instance is located in the specified inheritance tree, it returns GetType
. It is usually used to check whether the object is a specific type or its derivative type. For example:
<code class="language-csharp">object obj1 = 5; if (obj1.GetType() == typeof(int)) // 一些代码</code>
Main differences is
is
: Operation during compilation, provide type information based on the specified type name. true
<code class="language-csharp">object obj1 = 5; if (obj1 is int) // 一些代码</code>
: Operation during runtime, retrieve the actual type of instance.
typeof
Precautions GetType
It is useful when checking the instance type, such as in dynamic code scenarios. The operator is convenient to check the inheritance relationship during runtime. is
Consider the following code: In this example, if is an instance of ,
will return, because typeof
inherit GetType
. However, and return is
when
instances. Back when is
instance.The above is the detailed content of How Do `typeof`, `GetType`, and `is` Differ in C# Type Checking?. For more information, please follow other related articles on the PHP Chinese website!