What is the difference between IS and AS keyword in C#?
both operator is used for object conversion. Is operator is a boolean type operator. so it return true if succeed case and return false in the fail case.on the other hand As operator return null if conversion fail.
//The is operator is used to check whether the run-time type of an object is compatible with a given object num=10; if (num is int) { Response.Write("Num is integer"); } //The as operator is used to perform conversions between compatible types. object ss = "This sis the string"; string str = string.Empty; if (ss is string) { str = ss as string; Response.Write(str); }
There are a few keywords one should be aware of:
The as operator is similar to a cast but on any conversion failure null is returned as oppose to raising an exception. Note: it will not do the conversion (cast != data type conversion)!
Personally, I prefer not to use this operator, and, instead, use:
if (x is MyType)
// do the logic
else
// log error
As you can see, the is operator, which existed for some time, is used to check whether the run-time type of an object is compatible with a given type.
However, there are cases where as operator is useful. For example, I've personally used it in helper classes as described by code snippet below:
public class CompareHelper
{
public int Compare(object data1, object data2) // similar to string.compare
int result = 0;
if (typeof(T) == typeof(bool))
result = Compare(data1 as bool, data2 as bool);
else if (typeof(T) == typeof(string))
result = Compare(data1 as string, data2 as string);
else if (typeof(T) == typeof(SomeCustomClass)) // perhaps this calls for some property call
result = Compare(data1 == null ? 0m : (data1 as SomeCustomClass).SomeDecimalProperty, data2 == null ? 0m : (data2 as SomeCustomClass).SomeDecimalProperty);
. . .
}
public int Compare(bool data1, bool data 2)
public int Compare(decimal data1, decimal data 2)