Monday, June 4, 2007

Use the "as" Operator for Reference Type Casting

Normally, people do casting in the code like this:


Button btnSave = (Button) sender ;


Where sender is of Object Type

This same casting can be done using the as operator:


Button btnSave = sender as Button;


There are two advantages to using the ‘as’ operator:

·         It makes your code more readable.

·         If a type mismatch occurs, the object will become null instead of throwing an exception.


Following is the code sample with which we can test this:

public partial class _Default : System.Web.UI.Page


    Object obj1 = new Object();


    protected void Page_Load(object sender, EventArgs e)


        obj1 = "String";   



    protected void Button1_Click(object sender, EventArgs e)


        //This statement will throw an exception

        TextBox t1 = (TextBox)obj1;


    protected void Button2_Click(object sender, EventArgs e)


        //This will not throw any exception

        TextBox t1 = obj1 as TextBox;




Note: This only works for reference types.



Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258


DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

No comments:

Post a Comment