1

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?

asked Jun 1, 2016 at 22:38
3
  • 2
    No, string is reference type default is null. Commented Jun 1, 2016 at 22:40
  • 2
    String is a reference type. It defaults to null. You may or may not care. Commented Jun 1, 2016 at 22:40
  • 2
    String.Empty is the same as "" Commented Jun 1, 2016 at 22:55

3 Answers 3

3

Those lines of code are not equivalent.

  • If you've declared string status outside of a method, it initializes to its default value of null.

  • 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.

answered Jun 1, 2016 at 22:49

Comments

2

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;
answered Jun 1, 2016 at 22:49

Comments

1

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

answered Jun 1, 2016 at 22:53

1 Comment

will create a string object with a Null value wrong, that only happens on class-level variables, on a method it will not compile as it will be uninitialized.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.