Occasionally I want to break apart a constant string for formatting reasons, usually SQL.
const string SELECT_SQL = "SELECT Field1, Field2, Field3 FROM TABLE1 WHERE Field4 = ?";
to
const string SELECT_SQL = "SELECT Field1, Field2, Field3 "
+ "FROM TABLE1 "
+ "WHERE Field4 = ?";
However the C# compiler will not allow this second form to be a constant string. Why?
C string constants can be declared using either pointer syntax or array syntax: // Option 1: using pointer syntax. const char *ptr = "Lorem ipsum"; // Option 2: using array syntax.
A string constant is an arbitrary sequence of characters that are enclosed in single quotation marks (' '). For example, 'This is a string'. You can embed single quotation marks in strings by typing two adjacent single quotation marks.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
Concatenation is the process of combining two or more strings to form a new string by subsequently appending the next string to the end of the previous strings. In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
Um, that should be fine... are you sure it doesn't compile?
Sample code:
using System;
class Test
{
const string MyConstant = "Foo" + "Bar" + "Baz";
static void Main()
{
Console.WriteLine(MyConstant);
}
}
My guess is that in your real code you're including some non-constant expression in the concatenation.
For example, this is fine:
const string MyField = "Field";
const string Sql = "SELECT " + MyField + " FROM TABLE";
but this isn't:
static readonly string MyField = "Field";
const string Sql = "SELECT " + MyField + " FROM TABLE";
This is attempting to use a non-constant expression (MyField
) within a constant expression declaration - and that's not permitted.
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