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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top