Thoughts from the office by Ed Ball
Tuesday, January 27, 2004

Be sure to read Ian Griffiths' article on casting in C#. C# uses a C-style cast for two quite different operations -- to unbox a boxed value type, and to coerce a value from one type to another. One cast can't do both jobs, so, for example, if you have an object with an Int64 in it, you can't cast it directly to an Int32; you'll have to first cast it from an object to an Int64 and then to an Int32.

object longVal = 42L;
int intVal = (int) ((long) longVal);

His last point resonates with me the most. Why did they choose to use the C-style cast? I've been well-trained by C++ gurus that the C-style cast is evil, and I cringe every time I have to use it in C#. Besides, it's horribly ugly, and produces far too many parentheses. The as keyword is far more beautiful, and I find myself wanting to use it even when I should use a cast (for one thing, as is slightly less efficient than a cast when you know that the object is the desired type).

Console.WriteLine(((Derived)(myArray[i])).DoSomething());
// vs.
Console.WriteLine((myArray[i] as Derived).DoSomething());

So, how about a new keyword that works like as, but throws an exception if the cast fails? Separate keywords for casting and boxing? Any ideas?

Console.WriteLine((myArray[i] cast Derived).DoSomething());
1/27/2004 3:21:16 PM (Pacific Standard Time, UTC-08:00) | Comments [0] | Code#
Search
Archive
Links
Categories
Administration
Blogroll