Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not assign the concatenation of constant strings to a constant string?

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?

like image 381
C. Ross Avatar asked Feb 23 '11 14:02

C. Ross


People also ask

How do you declare a string constant?

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.

Can a constant Be a string?

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.

What is the correct way to concatenate the strings?

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.

Can you use += for string concatenation?

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.


1 Answers

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.

like image 67
Jon Skeet Avatar answered Oct 10 '22 03:10

Jon Skeet