Character Arithmetic

Strictly speaking, we’ve already covered arithmetic with the character type because it involves integral arithmetic. I want to take a look at it separately, though, because syntactically it might look a bit weird at first. Here is an example of some operations:

int numberOfLetters = 'z' - 'a' + 1;char e = (char)('a' + 4);

On the first line, two character literals are being subtracted. How does this work? Recall that characters are represented in 2 bytes to be able to represent Unicode characters. In fact, C# doesn’t directly specify arithmetic operations for integral types with a precision of less than 4 bytes. That’s why our discussion about integral arithmetic only mentioned int, uint, long, and ulong types.

What’s happening ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.