C. Ross
C. Ross

Reputation: 31848

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?

Upvotes: 7

Views: 6959

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499950

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.

Upvotes: 30

Related Questions