
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to use ‘as’ operator in C#?
The "as" operator perform conversions between compatible types. It is like a cast operation and it 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.
The following is an example showing the usage of as operation in C#. Here ‘as’ is used for conversion:
string s = obj[i] as string;
Try to run the following code to work with ‘as’ operator in C# −
Example
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!"); } Console.ReadKey(); } }
Output
0: 'jack' 1: This is not a string!
- Related Articles
- How to use ‘is’ operator in C#?
- How to use Operator Overloading in C#?
- How to use Null Coalescing Operator (??) in C#?
- How to use an assignment operator in C#?
- How to use the ?: conditional operator in C#?
- How do I use the conditional operator in C/C++?
- How to use delete Operator in TypeScript?
- How to use typeof operator in TypeScript?
- How to use the "in" operator in JavaScript?
- How to use the instanceof operator in Java?
- How to use *= operator in jQuery attribute selector?
- How to use the slicing operator in Python?
- Why do we use comma operator in C#?
- How to make use of both Take and Skip operator together in LINQ C#?
- How do I use the ternary operator ( ? : ) in PHP as a shorthand for “if / else”?

Advertisements