I have many scenarios in my application where I am declaring strings as string.empty and later dynamically adding values to it. In C#, Is
string status
and
string status = String.Empty;
same?
3 Answers 3
Those lines of code are not equivalent.
If you've declared
string status
outside of a method, it initializes to its default value ofnull
.If you've declared
string status
inside a method, it isn't initialized, and you can't use it until you explicitly give it a value.
Whether or not you need string status = String.Empty;
depends on your situation, but it seems like a decent way of avoiding a NullReferenceException
if you find your code sometimes throws.
Comments
No. It's not the same. String datataype allows null. And remember that it is encouraged that you always initialize all your variables/attributes/properties.
string status = String.Empty;
Comments
No, the default value of string variable is Null
string status;
- when inside a method: it would stay uninitialized
- when outside a method: it would create a string object with a Null value, because string is a reference type.
string status = String.Empty;
will create a string object with a value of the Empty constant which is a string of zero length
null
. You may or may not care.