DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

"as" operator keyword in C#.NET

By Ashok Nalam on 28 Nov 2013 | Category: C# | Tagged: keyword operator 
The article discuss about "as" operator keyword with Examples and shows difference between as keyword and cast expression.
  Discuss Add Comment   |  
Add rating Rate this resource   

Introduction:

 "as" operator keyword is used to perform conversions between reference/nullable/boxing types.

Syntax:

[ expression as type ]
where expression = expression of type (objName)
type = reference type
string value = refObject as string;
if ( refObject != null)
{
    // refObject is of string type.
}

Example: 

namespace DotNetMirror
{
    class asOperatorKeyword
    {
        static void Main()
        {
            Mirror objM = new Mirror();
            Console.WriteLine("objM = {0}", objM == null ? "null" : objM.ToString());
            ConvexMirror objCM = new ConvexMirror();
            Console.WriteLine("objCM = {0}", objCM == null ? "null" : objCM.ToString());

            ConvexMirror objMasCM = objM as ConvexMirror;
            Console.WriteLine("objMasCM = {0}", objMasCM == null ? "null" : objMasCM.ToString());

            //as like Cast      
            object obj = new Mirror();
            string objasString = obj as string;
            Console.WriteLine("objasString = {0}", objasString == null ? "null" : objasString);
            Console.ReadLine();
        }
    }
    class Mirror
    {
    }
    class ConvexMirror : Mirror
    {
    }
}

Output: 

as keyword example using C#.NET

"as" like Cast: 

as operator is same like cast except that it returns null on conversion failure instead of throwing an exception.
{ expression as type }  =  { expression is type ? (type)expression : (type) null }
object obj = new Mirror();
string str = obj as string;
Console.WriteLine("obj = {0}", str == null ? "null" : objCM.ToString());
If observe  above code obj is of type Mirror, but we performed conversion to string using "as" keyword. Object obj is not of type string so it returns null and prints null.

as with Nullable Types:

int? i = null;
Console.WriteLine("i = {0}", i as int? == null ? "null" : i.ToString());

Note : "as" operator performs only reference/nullable/boxing conversions and it can't perform other conversions like user-defined conversions. In order perform other conversions use cast expressions.
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9026  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.