CodeBork | Tales from the Codeface

The coding blog of Alastair Smith, a software developer based in Cambridge, UK. Interested in DevOps, Azure, Kubernetes, .NET Core, and VueJS.


Project maintained by Hosted on GitHub Pages — Theme by mattgraham

In Java, there’s only one way to explicitly cast a variable from one type to another, and that’s using the bracket syntax. In .NET (well, C# anyway), there are a couple: the Java-esque bracket syntax and the as keyword. Whilst I have used both frequently in the past, a situation occurred a couple of days ago where I realised I needed to clarify what as did under the hood. I was working through the Java examples of Test-Driven Development by Example in C# using the MSTest framework included with Visual Studio 2008 when I came across some funny polymorphism and casting that seemed valid in the example but wouldn’t compile in C#. It later transpired that I’d missed a step in the super-class, but as I tried the two different methods of casting, I realised they were different and I wasn’t sure how.

In C#, the explicit cast bracket syntax is identical to that in Java:

Java char x = 'x'; int y = (int) x;
C# char x = 'x'; int y = (int) x;

Under the hood, this also works the same way as it does in Java: it attempts to cast the one type to the other, and throws an exception if the types are not compatible.

Both languages also support implicit casting, which allows you to do things like:

int x = 10; long y = x;

C# also provides an as keyword for reference types; it won’t work on value types like int, double, etc. This is a second form of explicit casting, and it is used as follows:

Superclass superclass = new Superclass(); Subclass obj = superclass as Subclass;

This is a nifty trick, providing a form of checked casting. What happens when you use the as keyword is that the type is cast as before, but if the cast to Subclass fails, obj is set to null. Under the hood, this is what happens:

expression is type ? (type)expression : (type)null

(where is is C#’s equivalent of Java’s instanceof). Note that in this example expression is only evaluated one for the entire statement.

This is rather basic C# stuff, but sometimes you get a situation where it helps to remind yourself what’s going on behind the high-level constructs.