1

I'm wondering if I should use const string when using code like this:

    public DataTable GetSomeData(int id)
    {
        var con = new SqlConnection(ConnString);
        const string sql = "SELECT * FROM [data] WHERE [id]=@id";
        var cmd = new SqlCommand(sql, con);
        cmd.Parameters.AddWithValue("@id", id);

        var dt = new DataTable();
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        dt.Load(dr);
        con.Close();

        return dt;
    }

ReSharper suggested I solved it this way, but I'm told I shouldn't because it's not really constant. It changes when the parameters are added. I thought this way was proper because it's constant on the server running the code and only changes when it reaches the database.

So, what is the best way to do this?

1
  • 1
    "It changes when the parameters are added" - what does? sql doesn't... Commented May 24, 2012 at 16:21

1 Answer 1

7

The string with the placeholders of parameters should be constant and it is right to declare it as a constant, it is the command object that is mutable, but the query string is constant and immutable .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.