public abstract class Animal{}
public class Cat : Animal
{}
public class Ornament
{
public static explicit operator Ornament(Cat cat)
{
return new Ornament();
}
}
class Program
{
static void Main()
{
Cat cat = new Cat();
// This line fails to compile
Ornament jug = cat as Ornament;
// this works with our explicit operator defined for Ornament
Ornament anotherJug = (Ornament)cat;
}
}
Well the holes in my C# knowledge never cease to amaze me, I mean, I knew what I could do with the as keyword but I did not know the subtle difference it has to a direct cast.
By using the as keyword to cast from one type to another, if the cast is not possible it will result in a null, however using a direct cast will throw an exception.
An example demonstrates the use of the as keyword.
public abstract class Animal{}
public class Cat : Animal{}
public class Ornament{}
class Program
{
static void Main()
{
object cat = new Cat();
// jug will be null after this conversion since
// cat is not an Ornament
Ornament jug = cat as Ornament;
// this throws an InvalidCastException
jug = (Ornament) cat;
// This works since Cat is an Animal, animal will not
// have a reference to cat
Animal animal = cat as Animal;
}
}
Quite handy really, but there is one thing to note, notice that we say object cat = new Cat();? This is because we get a compilation error if we had used Cat cat = new Cat();
Cannot convert type 'ConsoleApplication1.Cat' to 'ConsoleApplication1.Ornament' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
The reason for this (I believe) is because of the limitation described in the MSDN Docs for the as keyword.
Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
An example below shows this, it has been slightly modified by adding an explicit cast operator to Ornament so we can use a cast expression for anotherJug to show the difference between a cast and a conversion with the as keyword, so as the docs say:- user-defined conversions do not work with the as keyword.