Mr. Flibble
Mr. Flibble

Reputation: 341

C# - Is this declared string treated as a const?

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?

Upvotes: 6

Views: 739

Answers (6)

Michael Stum
Michael Stum

Reputation: 181124

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 :)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504052

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.

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1064244

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).

Upvotes: 2

rgargente
rgargente

Reputation: 1840

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.

Upvotes: 0

Alex Reitbort
Alex Reitbort

Reputation: 13706

Yes, those are exactly the same.

Upvotes: 1

ThorHalvor
ThorHalvor

Reputation: 627

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

Upvotes: 1

Related Questions