Ray's playground

 

Item 3: Prefer the is or as Operators to Casts(Effective C#)

  Remember that user-defined conversion operators operate only on the compile-time type of an object, not on the runtime type.
  Now that you know to use as when possible, let’s discuss when you can’t use it. The as operator does not work on value types. 
  The is operator should be used only when you cannot convert the type using as. Otherwise, it’s simply redundant.
  foreach uses a cast operation to perform conversions from an object to the type used in the loop. foreach needs to use casts to support both value types and reference types. By choosing the cast operator, the foreach statement exhibits the same behavior, no matter what the destination type is. However, because a cast is used, foreach loops can cause an InvalidCastException to be thrown.
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 
 7 namespace EffectiveCSharpItem3
 8 {
 9     public class MyType 
10     {
11     }
12 
13     public class SecondType 
14     {
15         private MyType type = new MyType();
16 
17         public static implicit operator MyType(SecondType t)
18         {
19             return t.type;
20         }
21     }
22 
23     class Program
24     {
25         static void Main(string[] args)
26         {
27             SecondType st = new SecondType();
28             MyType t = (MyType)st;
29 
30             IEnumerable collection = new List<int>() { 12345678910 };
31             var small = from int item in collection
32                         where item < 5
33                         select item;
34             var small2 = collection.Cast<int>().Where(item => item < 5);
35             foreach (int i in small) 
36             {
37                 Console.WriteLine(i);
38             }
39 
40             foreach (int i in small2)
41             {
42                 Console.WriteLine(i);
43             }
44             Console.WriteLine(t == null);
45             Console.Read();
46         }
47     }
48 }

 

 

posted on 2011-01-09 11:16  Ray Z  阅读(213)  评论(0编辑  收藏  举报

导航