This
Class c = new BaseClass() as Class;
is totally useless. If Class
is a base class of BaseClass
then the cast was automatic, otherwise the cast will always return null
.
Class c = new BaseClass()
was enough... Single exception:
var c = new BaseClass() as Class;
now c
is a reference of type Class
(but referencing a BaseClass
). You are forcing the type of an implicit typed variable (quite useless... you could have written directly Class c = new BaseClass();
)
Note that the as
keyword, contrary to the cast operator ()
doesn't "activate" the implicit
/explicit
cast operator that one of the two classes could have implemented.
This won't compile:
class BaseClass
{
public static implicit operator Class(BaseClass b)
{
return new Class();
}
}
class Class
{
}
Class c = new BaseClass() as Class;
As written in the msdn:
The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.
and
Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.