Preferred way to set default values ​​for values ​​valid for NULL?

I have a dilemma. The task (reduction) is to remake the next data holder class

class Stuff { public String SomeInfo { get; set; } } 

to satisfy the requirement that null is not returned. I can think of two ways to achieve this, and after looking deeply at 15 minutes, I just can't decide which one is preferable.

Designer approach.

 class Stuff { public String SomeInfo { get; set; } public Stuff() { SomeInfo = String.Empty; } } 

Property Approach.

 class Stuff { private String _SomeInfo; public String SomeInfo { get { return _SomeInfo ?? String.Empty; } set { _SomeInfo = value; } } } 

Note that creating instances of Stuff can be done using the constructor, as well as initialization, if that matters. As far as I know, there will be no other restrictions (but you know how customer specifications do not always reflect reality).

+8
c # properties
source share
3 answers

You can only guarantee that null never returned when using the property:

 class Stuff { private String _SomeInfo; public String SomeInfo { get { return _SomeInfo ?? String.Empty; } set { _SomeInfo = value; } } } 

The same approach is used by textual controls (for example, in ASP.NET), where the Text property never returns null , but String.Empty .

For example ( ILSpy ):

 // System.Web.UI.WebControls.TextBox public virtual string Text { get { string text = (string)this.ViewState["Text"]; if (text != null) { return text; } return string.Empty; } set { this.ViewState["Text"] = value; } } 
+17
source share

You can also implement the logic in the installer and not in the getter, so your back margin always has a valid value

 class Stuff { private String _SomeInfo = string.Empty; public String SomeInfo { get { return _SomeInfo; } set { if (value != null) { _SomeInfo = value; } } } } 
+5
source share

To add another answer to this, you can also set the default value for the string object in one expression:

 class Stuff { private String Something {get; set;} = string.Empty; } 
+4
source share

All Articles