Hi Guys
NP145 as operator
It is said that as operator is used to perform conversions between compatible types.
Here what is meant by compatible types. In the following program Drived class is inherited from Base class therefore can we say both the Drived class and Base class are compatible. Is that the reason as has been used.
I wish to whether my understanding is correct.
Please confirm.
Thank you
using System;
class csrefKeywordsOperators
{
class Base
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
}
}
}
}
//Base
Posted Sep 14, 2008, 7:40 PM
Thank you very much for explanation, Alan
Base b = d as Base;
is similar to:
Base b = (Base)d;
Above step made it easy to understand the "as"
AlanPosted Sep 14, 2008, 7:04 PM
The 'as' operator differs from a cast in several respects:
1. It can only be used with reference types or when boxing value types.
2. It can't be used with user defined conversions.
3. It never throws an exception. If the conversion is not possible, the result is null. This in fact is the usual reason for preferring it to a cast.
Apart from that it behaves like the normal cast operator. In particular the types have to be compatible and a derived class and its base class are compatible for the conversion to succeed, as you rightly say.
So the following line:
Base b = d as Base;
is similar to:
Base b = (Base)d;
but if 'd' hadn't been a Derived object but an object of some incompatible type, then the first expression would have returned null but the second would have thrown an exception.
It doesn't matter which is used in the example program and so it's not a very good one IMO.