In this tutorial,we’ll learn 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:
1 2 3 |
string s = obj[i] as string; |
Try to run the following code to work with ‘as’ operator in C# −
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Demo { public static void Main() { object[] obj = new object[2]; obj[0] = "csharp"; 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:
1 2 3 4 |
0: 'jack' 1: This is not a string! |