Search This Blog

Friday, January 2, 2009

"As" Keyword in C#

"As" Keyword in C# - When to use?
  1. As keyword is used for the comparison of compatible types
  2. Its general syntax is expression as type where expression is also a reference type and type is also a reference type.
  3. 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.
  4. So when to use as keyword and when to use cast expression is a very important question indeed.
  5. Both have their individual significance.
  6. 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.
  7. 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:-

 

 1: using System;
 2:  
 3: namespace Ramp.Test
 4: {
 5: class Program
 6: {
 7: static void Main(string[] args)
 8: {
 9: var myObject = new object[3];
 10: myObject[0] = new Student();
 11: myObject[1] = new Teacher();
 12: myObject[2] = "I love C#";
 13:  
 14: foreach (object obj in myObject)
 15: {
 16: string s = obj as string;
 17: if(s!=null)
 18: Console.WriteLine("It is a string");
 19: else
 20: {
 21: Console.WriteLine("Its not a string");
 22: }
 23: Console.ReadLine();
 24: }
 25: 
 26: }
 27: }
 28: public class Student
 29: {
 30: 
 31: }
 32: public class Teacher
 33: {
 34: 
 35: }
 36: }

 

Output

Its not a string
Its not a string
Its a string

No comments:

 
ss_blog_claim=610c329374fdaea5e07dfca1c6dffb2d