views:

255

answers:

6

Help me settle an argument here.

Is this:

SqlCommand cmd = new SqlCommand( "sql cmd", conn);

treated exactly the same as this:

const string s = "sql cmd";
SqlCommand cmd = new SqlCommand( s, conn);

Ie. does it make a difference if I state specifically that the string s is a const.

And, if it is not treated in the same way, why not?

A: 

the constructor of the SqlCommand will not "see" any difference, and will therefore act the same way.

ThorHalvor
+1  A: 

Yes, those are exactly the same.

Alex Reitbort
+6  A: 

In the latter snippet, it's not that the string is const - it's that the variable is const. This is not quite the same as const in C++. (Strings are always immutable in .NET.)

And yes, the two snippets do the same thing. The only difference is that in the first form you'll have a metadata entry for s as well, and if the variable is declared at the type level (instead of being a local variable) then other methods could use it too. Of course, due to string interning if you use "sql cmd" elsewhere you'll still only have a single string object in memory... but if you look at the type with reflection you'll find the const as a field in the metadata with the second snippet if it's declared as a constant field, and if it's just a local variable it'll be in the PDB file if you build one.

Jon Skeet
A: 

I'm not 100% sure about this, but I'd bet it is the same.

const will just make sure you don't reassing the variable, but it's something that can be done at compile time.

Morover, strings are inmutable, so I don't think it will make any difference declaring the variable or not.

However, the definite prove would be studing the IL code generated in both cases.

Rafa G. Argente
That sounds more like you are describing `readonly` - `const` does more than that (the value is copied **directly** by callers - it isn't a "Ldfld" / "Ldsfld".
Marc Gravell
Sorry but I don't understand you completely. What you mean when you say "the value is copied **directly** by callers"?From MSDN: a const field is a compile-time constanthttp://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
Rafa G. Argente
+2  A: 

The value of a const always gets burned directly into the caller, so yes they are identical.

Additionally, the compiler interns strings found in source code - a const is helpful if you are using the same string multiple times (purely from a maintenance angle - the result is the same either way).

Marc Gravell
+1  A: 

Yes, feel free to use Reflector to look at the assembly, const strings will be replaced with literal strings on compilation. I also have a blog post about this to safe you the work of using Reflector :)

Michael Stum
All literal strings will be interned by the current CLR. It has nothing to do with const, which only affects the variable not the string instance itself (but strings are immutable in .NET)
Brian Rasmussen