I want to know which is the preferred way to declare a string in C#:
string strEmpty = String.Empty;
or
string strNull = null;
Which practice is better or what is the difference between these statements.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
the first answer makes the value of the string an actual empty string. Assigning it to null makes the pointer point to nothing. This means that if you tried to do strEmpty.Function(), it wouldn’t work in the second case.
The first takes more memory initially, but is more clear.
The correct answer depends on what you would do next. If you are just going to reassign the string, I would make it
null. If you intend to do stuff to the string (execute functions, append, etc), I would make itstring.empty.