- e as T : yields e as type T if (E is T), null otherwise
- (T)e : yields e as type T if (E is T), exception otherwise
So, you should use "(T)e" where you want immediate failure if E is not
of type t, and "e as T" when you want some behaviour on e, even if it is
not of type T
Example:
class Foo: IComparable {
int i;
public int CompareTo(Object arg0) {
Foo other = arg0 as Foo;
if ( other == null )
return 1;
else
return i - other.i;
}
public override bool Equals(Object arg0) {
Foo other = (Foo)arg0;
return i == other.i;
}
}
please dont do:
public void foo(Object o) {
Foo foo = o as Foo;
if ( foo == null )
throw new ArgumentException("must be instance of Foo", "o");
or, worse:
public void foo(Object o) {
Foo foo = o as Foo;
...
foo.f(x); // throws NullReference if o is not a Foo
Since:
public void foo(Object o) {
Foo foo = (Foo)o;
Gives a much more precise error-path
and using the as operator is simply that as works on references rather
than on primitive data types. So using the as operator in C# should be
roughly equivalent to casting a pointer type to another in C.
No, its like casting pointers with dynamic_cast in _C++_. In C, casts
have no runtime-meaning, they do in C++ (with RTTI...):
C++ C#
dynamic_cast<T>(e) ~ (T)e
dynamic_cast<T*>(e) ~ e as T
I would
like to know though, does anything in particular happen when a concersion
from one reference type to another takes place in C# using the as keyword?
Nah,
In particular, how does the as keyword work under the hood?
Nothing happens, you can psuedo-code "as" yourself:
public static T as(Object o) {
if ( o is T )
return (T)o;
else
return null;
}
--
Helge