I code in C# primarily these days, but I coded for years in VB.NET. In VB, I could combine a character constant and a string literal to create other constants, which is very handy:
Const FileExtensionSeparatorCharacter As Char = "."c
Const BillingFileTypeExtension As String = FileExtensionSeparatorCharacter & "BIL"
Now I'd like to do the same in C#:
const char FileExtensionSeparatorCharacter = '.';
const string BillingFileTypeExtension = FileExtensionSeparatorCharacter + "BIL";
but this give me a compiler error:
The expression being assigned to 'BillingFileTypeExtension' must be constant
Is there a reason I can't do this in C#?
Character Constants are written by enclosing a character within a pair of single quotes. String Constants are written by enclosing a set of characters within a pair of double quotes.
Concatenate string literals in C/C++ A string literal is a sequence of characters, enclosed in double quotation marks (" ") , which is used to represent a null-terminated string in C/C++. If we try to concatenate two string literals using the + operator, it will fail.
String Literals. A String Literal, also known as a string constant or constant string, is a string of characters enclosed in double quotes, such as "To err is human - To really foul things up requires a computer." String literals are stored in C as an array of chars, terminted by a null byte.
The concat() method joins two or more strings. The concat() method does not change the existing strings. The concat() method returns a new string.
Is there a reason I can't do this in C#?
Yes, but you're not going to like it. The string concatenation involved in char + string
involves implicitly calling ToString()
on the char
. That's not one of the things you can do in a constant expression.
If you make them both strings, that's fine:
const string FileExtensionSeparator = ".";
const string BillingFileTypeExtension = FileExtensionSeparator + "BIL";
Now that's string + string
concatenation, which is fine to occur in a constant expression.
The alternative would be to just use a static readonly
field instead:
const char FileExtensionSeparatorCharacter = '.';
static readonly string BillingFileTypeExtension = FileExtensionSeparatorCharacter + "BIL";
I have to assume here that adding a character to a string is not considered a compile time constant, but rather a a run-time operation. If you change the type of FileExtensionSeparatorCharacter to string you will compile just fine.
const string FileExtensionSeparatorCharacter = ".";
const string BillingFileTypeExtension = FileExtensionSeparatorCharacter + "BIL";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With