Monday, November 17, 2008

C#----When to use As Keyword in C#

  1. As keyword is a hidden treasure in C# which most of us don't use in our day today programming.
  2. As keyword is used for the comparison of compatible types
  3. Its general syntax is expression as type where expression is also a reference type and type is also a reference type.
  4. Whenever there is nothing in the object instead of complaining to user or throwing an exception it just returns "null" thus it doesn't throw an exception.
  5. So when to use as keyword and when to use cast expression is a very important question indeed.
  6. Both have their individual significance.
  7. Whenever you do not want to raise any exception and you have already handled the returned null value condition then it  is wiser to use "As" keyword.
  8. But when you want that whenever the object is null an exception should be raised and you are using exception handling then you always must use the same familier cast expressions.

Given below is a small code snippet to demonstrate that:-

using System;
namespace Ramp.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var myObject = new object[3];
            myObject[0] = new Student();
            myObject[1] = new Teacher();
            myObject[2] = "I love C#";

            foreach (object obj in myObject)
            {
                string s = obj as string;
                if (s != null)
                    Console.WriteLine("It is a string");
                else
                {
                    Console.WriteLine("Its not a string");

                }
                Console.ReadLine();
            }
        }
    }

    public class Student
    {

    }

    public class Teacher
    {

    }

}



Output

Its not a string 
Its not a string 
Its a string

3 comments :

Anonymous said...

"As" a quite slower then to use (ClassName) notation, so you should avoid it :)

Claus Jørgensen said...

Another advantage is syntax ;)

(foo as Bar).Property

versus:

((Bar)foo).Property

Anonymous said...

wouldn't raise
(foo as Bar).Property
a Null Reference Exception if foo is not type compatible with Bar thus "As" will return Null?

Post a Comment