Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use 'as' operator in C#?
The as operator in C# performs safe type conversions between compatible reference types. Unlike direct casting, the as operator returns null if the conversion fails instead of throwing an exception, making it ideal for checking type compatibility.
The as operator can perform reference conversions, nullable conversions, and boxing conversions, but cannot perform user-defined conversions or value type conversions (except nullable types).
Syntax
Following is the syntax for using the as operator −
TargetType variable = expression as TargetType;
If the conversion succeeds, variable contains the converted value. If it fails, variable is null.
Using 'as' for Safe Type Conversion
The as operator provides a safe way to attempt type conversion without risking exceptions −
using System;
public class Demo {
public static void Main() {
object[] obj = new object[2];
obj[0] = "jack";
obj[1] = 32;
for (int i = 0; i < obj.Length; ++i) {
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("This is not a string!");
}
}
}
The output of the above code is −
0: 'jack' 1: This is not a string!
Using 'as' with Class Inheritance
The as operator works well with inheritance hierarchies for safe downcasting −
using System;
class Animal {
public virtual void MakeSound() {
Console.WriteLine("Some generic animal sound");
}
}
class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Woof!");
}
public void Fetch() {
Console.WriteLine("Fetching the ball!");
}
}
class Program {
public static void Main() {
Animal[] animals = { new Dog(), new Animal() };
foreach (Animal animal in animals) {
Dog dog = animal as Dog;
if (dog != null) {
dog.Fetch();
} else {
Console.WriteLine("Not a dog");
}
}
}
}
The output of the above code is −
Fetching the ball! Not a dog
Comparison: 'as' vs Direct Cast
| 'as' Operator | Direct Cast (Type) |
|---|---|
Returns null on failure |
Throws InvalidCastException on failure |
| Safe conversion, no exceptions | Unsafe, can cause runtime errors |
| Works only with reference types | Works with value and reference types |
| Requires null check after conversion | No null check needed if successful |
Example Comparing Both Approaches
using System;
class Program {
public static void Main() {
object obj = "Hello World";
// Using 'as' operator - safe
string str1 = obj as string;
if (str1 != null) {
Console.WriteLine("Using 'as': " + str1);
}
// Direct cast - can throw exception
try {
string str2 = (string)obj;
Console.WriteLine("Direct cast: " + str2);
} catch (InvalidCastException) {
Console.WriteLine("Cast failed");
}
// Testing with incompatible type
object number = 42;
string str3 = number as string; // Returns null
Console.WriteLine("Number as string: " + (str3 ?? "null"));
}
}
The output of the above code is −
Using 'as': Hello World Direct cast: Hello World Number as string: null
Conclusion
The as operator provides safe type conversion in C# by returning null instead of throwing exceptions when conversion fails. It's particularly useful when working with object hierarchies and when you need to check if an object is of a specific type before performing type-specific operations.
