as Keyword in c#

'as' Keyword in c#

 In many cases, we need to convert an Object(Type) into another Object(Type) and sometimes you may get InvalidCastException. So, to overcome such types of exceptions C# provides as operator keyword.

This operator returns the object when they are compatible with the given type and returns null if the conversion is not possible instead of throwing an exception.

'as' keyword checks the compatibility of one object type with another object type. In the case of compatibility, it will return the value of the new object type otherwise, null will be returned.

Syntax of 'as' keyword


Expression as dataType;
using System; 
using System.Text; 
using System.Collections.Generic; 
class usingcsharp{     
    public static void Main() { 
        // taking a string variable 
        string str1 = "abc"; 
        // 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;           
        if(str2 != null) 
        // now try to cast it to List 
        List<string> mylist = obj1 as List<string>; 
        // checking Successfully cast or not 
        if(mylist != null) 
            Console.WriteLine("Not Successfull");