Declare a string type variable as a global variable in one aspx file, which is better initialized with null or string.empty

which is best for a global string type variable in one aspx page?

+1


source to share


3 answers


I personally use String.Empty, but the choice was coin transfer for me.



I believe that using String.IsNullOrEmpty()

my strings to validate means that it doesn't matter how they were initialized.

+1


source


Well, there is no need to initialize the field before null

- that will be automatic. And there isn't much benefit in string.Empty

just the pros ""

, which I find more readable (since the compiler automatically uses interned strings for any literals in the source code).

So personally I would use:

string foo = "";

      



or simply:

string foo; // defaults to null

      

I make it a habit to use string.IsNullOrEmpty

for most tests, which eliminates most of the differences between the two.

+1


source


It probably depends on how the variable will be used. If you don't need to check for empty strings, then initialize it to string.Empty to avoid doing null checks.

As an aside, placing a global variable in an ASPX page might not be the best choice for storing your data. Another class with the specific purpose of string manipulation might be better. Also, it would be safer to make the variable private and provide public properties or methods to access it - this way you can always ensure that the value is valid.

0


source







All Articles