Question

At the moment I maintain a quirky codebase, and came across the following same pattern more than 100 times:

string NotMySqlQuery = ""; //why initialize the string with "", only to overwrite it on the next line?
NotMySqlQuery = "The query to be executed";

Since I came across this so often, I now doubt my own good judgement.

Is this a trick to optimize the compiler or does it bring any other advantages?

It reminds me a bit of the old times when I did write some code in C++, but it still doesn't look like proper dealing with strings to me.

Why would someone write code like that?

Was it helpful?

Solution

There is no performance advantage of that syntax. It is even slightly worse than not initializing it at all, since the strings are immutable in c# and this way 2 separate strings are allocated.

OTHER TIPS

For your simple case, it is better to save the 2 lines into one, there is no point to assign it an empty string, and immediately assign another value to it.

string NotMySqlQuery = "The query to be executed";

This is clearer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top