문제

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