Mare Infinitus
Mare Infinitus

Reputation: 8182

Why is there no empty char literal?

Is there any specific reason why there is no empty char literal?

What comes closest to what I think of, the '' is the '\0' the null character.

In C++ the char is represented by an int, which means empty char goes directly to the 0 integer value, which is in C++ "the same as null".

The practical part of coming up with that question:

In a class I want to represent char values as enum attributes. Unbiased I tried to initialize an instance with '', which of course does not work. But shouldn't be there a char null value? Not to be confused with string.Empty, more in the nature of a null reference.

So the question is: Why is there no empty char?

-edit-

Seeing this question the question can be enhanced on: An empty char value would enable concatening strings and chars without destroying the string. Would that not be preferable? Or should this "just work as expected"?

Upvotes: 4

Views: 11424

Answers (3)

Flynn W SCT
Flynn W SCT

Reputation: 11

I think the best person to answer this one be someone on the C# design team. However, my best explanation would be that it all comes down to types and how type values are interpreted. In this case, the byte and char types have the same size and, for the most part, are interpreted the same way by mathematical/logical operators. The key difference is the history behind char and the fact that all of the values of the first 7 bits are defined by ASCII. The ASCII code with the numeric value of 0 is the null character, which is represented in C# by '\0'. Your main problem is one of precedence and that when C# was created, they built on top of prior conventions rather than throwing them away in favor of a fully consistent language.

I'm fairly certain that C# doesn't treat strings as null terminated like C. So, I think you can have a null character in the middle of a string and C# would still print all the way to the end, but I haven't verified this in a while.

All that said, your best bet might have been to use bytes and then convert to a string when you need to print.

Upvotes: 0

Douglas
Douglas

Reputation: 54887

To give a slightly more technical explanation: There is no character that can serve as the identity element when performing concatenation. This is different from integers, where 0 serves as the identity element for addition.

Upvotes: 3

Eugen Rieck
Eugen Rieck

Reputation: 65284

A char by definition has a length of one character. Empty simply doesn't fit the bill.

Don't run into confusion between a char and a string of max length 1. They sure look similar, but are very different beasts.

Upvotes: 6

Related Questions