In software development, typecasting is an inescapable thing. In many cases, developers 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 the operator keyword as.
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.
Syntax:
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.
CSharp
// C# program to illustrate
// the use of 'as' operator
using System;
using System.Text;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main() {
// taking a string variable
string str1 = "GFG";
// taking an Object type variable
// assigning var1 to it
object obj1 = str1;
// now try it to cast to a string
string str2 = obj1 as string;
// checking Successfully cast or not
if(str2 != null)
{
Console.WriteLine("Successfully Cast");
}
// now try to cast it to List
List<string> mylist = obj1 as List<string>;
// checking Successfully cast or not
if(mylist != null)
{
Console.WriteLine("Successfully Cast");
}
else
{
Console.WriteLine("Not Successful");
}
}
}
OutputSuccessfully Cast
Not Successful
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.
CSharp
// C# program to illustrate the
// concept of 'as' operator
using System;
// Classes
class Geeks1 { }
class Geeks2 { }
class GFG {
// Main method
static void Main()
{
// creating and initializing object array
object[] obj = new object[5];
obj[0] = new Geeks1();
obj[1] = new Geeks2();
obj[2] = "C#";
obj[3] = 334.5;
obj[4] = null;
for (int j = 0; j < obj.Length; ++j) {
// using as operator
string str = obj[j] as string;
Console.Write("{0}:", j);
// checking for the result
if (str != null) {
Console.WriteLine("'" + str + "'");
}
else {
Console.WriteLine("Is is not a string");
}
}
}
}
Output: 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
Similar Reads
C++ | Nested Ternary Operator Ternary operator also known as conditional operator uses three operands to perform operation. Syntax : op1 ? op2 : op3; Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : ca ? b: c ? d : e ? f : g ? h : ia ? b ? c : d : e Let us unde
5 min read
C# | Operator Overloading Prerequisite: Operators in C# The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use the same operator to do various operations. It provides additional capabilities to C# operators when they are applied to user-defined data types. It ena
4 min read
Relational Operators in C In C, relational operators are the symbols that are used for comparison between two values to understand the type of relationship a pair of numbers shares. The result that we get after the relational operation is a boolean value, that tells whether the comparison is true or false. Relational operato
4 min read
Unary Operators in C In C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
C++ Relational Operators In C++, Relational operators are used to compare two values or expressions, and based on this comparison, it returns a boolean value (either true or false) as the result. Generally false is represented as 0 and true is represented as any non-zero value (mostly 1).Syntax of Relational OperatorsAll C+
3 min read
What are Operators in Programming? Operators in programming are essential symbols that perform operations on variables and values, enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations. In this article, we will learn about the basics of operators and their types. Operators in Programming Table of
15+ min read