!as operator

Topics: C# Language Design
May 19, 2014 at 7:04 PM
the code like:
var  user = ((MyUIComponent)sender).user;
is not good readable.
the code like:
var  user = (sender as MyUIComponent).user;
better but in many situations if we not check result for null we receive exception in another code not on cast.

I propose:
var  user = (sender !as MyUIComponent).user;
That will act just like standart cast, so it is equivalent to:
var  user = ((MyUIComponent)sender).user;
BUT it's more readable :)

May 19, 2014 at 7:09 PM
May be !as need to be as!
May 19, 2014 at 8:28 PM
Took me a moment to realize what you were proposing there as !as definitely reads as "not as".

I actually would prefer the functional cast notation supported by C++ which plays better when you combine member access.

object obj = "Hello World!";

// C# style cast
int length = ((string)obj).Length;

// C++ functional-style cast
int length = string(obj).Length;

Issue here being that such syntax could easily collide with existing member names, although it could be treated like other contextual keywords like var and only be treated as a type cast when there isn't ambiguity.
May 19, 2014 at 8:45 PM
I don't see much point in defining another cast which is equivalent to an existing one. I could, however, see some usage cases for a casting operator whose semantics are different from present ones. What should your operator do when casting to SiameseCat a null reference of type Cat? What should it do if asked to convert a Cat-constrained generic to SiameseCat, or vice versa?