Got more questions? Find advice on: SQL | XML | Regular Expressions | Windows
in Search
Welcome to AspAdvice Sign in | Join | Help

C# Nuggets

Is a character a character?

The other day, I saw the following code:

data.TrimEnd(new char['|']);

which at first glance looks like it trims the pipe character from the end of the data string. But that's not what it does. In fact, it does nothing. Here's why.

In .Net, the character data type doesn't really exist - it's an illusion. Whenever you write code like:

char x='A';

All this is really doing is creating a new integer with the Unicode codepoint value for 'A'. However, up until today, I didn't realize there was an implicit datatype conversion defined for Char to Int - eg:

int x='A';

is perfectly valid code. The reverse is not true. The following will cause a compilation error:

char x=0x41;

Now, given what we know about implicit conversions of characters to integer, what do you suppose the following code does?

char[] x=new char['A'];

It will perform an implicit conversion of 'A' to the integer value 65 at compile time and use this to initialize a 65 element long array. It's a completely bizarre thing to write and a good way of making your code more obscure - but it may be a good idea to know what it does just in case you come across it in production code....

Sponsor
Published Friday, May 07, 2004 9:48 AM by rbirkby
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Enter the code you see below

Submit