In the development of the software, typecasting is an inescapable thing. In many cases, developer need to convert an Object(Type) into another Object(Type) and sometimes he/she may get InvalidCastException. So, to overcome such types of exception C# provides as operator keyword.
The as operator is used to perform conversion between compatible reference types or Nullable types. This operator returns the object when they are compatible with the given type and return null if the conversion is not possible instead of raising an exception. The working of as operator is quite similar to is an operator but in shortening manner.
expression as type
The above syntax is equivalent to below code. But the expression variable will be evaluated only one time.
expression is type ? (type)expression : (type)null
Here, ‘is‘ is an operator keyword.
Note: The ‘as’ operator keyword in C# is used only for nullable, reference and boxing conversions. It can’t perform user-defined conversions that can be only performed by using cast expression.
Example 1: In the below code, str1 contains a string which is assigned to a variable obj1 of the object type. Now, this obj1 is cast to string using as operator and assign the case result to variable str2 of string type. If the case successful, it returns the result otherwise returns null. Here, if(str2 != null) is used to check whether the result is null or not. For List<string> mylist = obj1 as List<string> cast fails and it returns null.
Successfully Cast Not Successfull
Example 2: In the code, we are taking an Object array which can store five elements. The first and second elements are the instance of class Geeks1 and class Geeks2. The third element is a string and the fourth element is a double value and the fifth element is a null value. Here, string str = obj[j] as string; we are using as operator to cast the object array as a string and store result into the string str. After that, check for the resultant value. If it is null then print the “element is not a string” and if not null, then print the string.
0:Is is not a string 1:Is is not a string 2:'C#' 3:Is is not a string 4:Is is not a string
- Is vs As operator keyword in C#
- C# | is Operator Keyword
- typeof Operator Keyword in C#
- int Keyword in C#
- var keyword in C#
- C# | this Keyword
- ulong keyword in C#
- bool Keyword in C#
- decimal keyword in C#
- byte Keyword in C#
- char keyword in C#
- C# | finally keyword
- LINQ | Let Keyword
- uint keyword in C#
- Static keyword in C#
- sbyte Keyword in C#
- short keyword in C#
- void Keyword in C#
- double Keyword in C#
- float keyword in C#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.