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#?
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";
See more on this question at Stackoverflow