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?
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
sas 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.