—Typeof operator and GetType Method
Used to obtain the System.Type object for a type. A typeof expression takes the following form:
System.Type type = typeof(int);
To obtain the run-time type of an expression, we can use the .NET Framework method GetType, as in the following example:
int i = 0;
System.Type type = i.GetType();
The typeof operator cannot be overloaded. typeof is applied to a type. GetType is applied to an object. In both cases the result is an object of the type System.Type containing meta-information on a type.
typeOf is a C# keyword that is used when we have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.
public class MySpecialTextBox : TextBox
{
}
MySpecialTextBox special = new MySpecialTextBox();
if (special is TextBox) ==> true
if (special.GetType() == typeof(TextBox)) ==> false
This sample uses the GetType method to determine the type that is used to contain the result of a numeric calculation. This depends on the storage requirements of the resulting number. This depends on the storage requirements of the resulting number.
—Is Operator
Checks if an object is compatible with a given type. For example, the following code can determine if an object is an instance of the MyObject type, or a type that derives from MyObject:
if (obj is MyObject)
{
}
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.
The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.
The is operator cannot be overloaded.
Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.
Anonymous methods are not allowed on the left side of the is operator. This exception includes lambda expressions.
–as operator
we use the as operator to perform certain types of conversions between compatible reference types or nullable types.
The as operator is like a cast operation. However, if the conversion isn’t possible, as returns null instead of raising an exception. Consider the following example:
expression as type
The code is equivalent to the following expression except that the expression variable is evaluated only one time.
expression is type ? (type)expression : (type)null
Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can’t perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.