Reputation: 39148
I'm in a dilemma. The (reduced) task is to redesign the following data holder class
class Stuff
{
public String SomeInfo { get; set; }
}
to accommodate the demand that null mustn't be returned. I can think of two ways to achieve that and after deep consideration of 15 minutes, I simply can't decide which one is to be preferred.
Approach by constructor.
class Stuff
{
public String SomeInfo { get; set; }
public Stuff() { SomeInfo = String.Empty; }
}
Approach by property.
class Stuff
{
private String _SomeInfo;
public String SomeInfo
{
get { return _SomeInfo ?? String.Empty; }
set { _SomeInfo = value; }
}
}
Note that the creation of the Stuff instances might be done using the constructor as well as initialization, if that's of any significance. As far as I'm informed, there won't be any other restrictions (but you know how the customers' specifications not always reflect the reality).
Upvotes: 13
Views: 58650
Reputation: 388
Just to add another answer to this, you can also set a default value to a string object in a single statement;
class Stuff
{
private String Something {get; set;} = string.Empty;
}
Upvotes: 11
Reputation: 38179
You can also implement the logic in the setter rather than in the getter, that way your back field always has a valid value
class Stuff
{
private String _SomeInfo = string.Empty;
public String SomeInfo
{
get { return _SomeInfo; }
set
{
if (value != null)
{
_SomeInfo = value;
}
}
}
}
Upvotes: 6
Reputation: 460158
You can only ensure that null
is never returned when you use the property:
class Stuff
{
private String _SomeInfo;
public String SomeInfo
{
get { return _SomeInfo ?? String.Empty; }
set { _SomeInfo = value; }
}
}
The same approach is used by text-controls(e.g. 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;
}
}
Upvotes: 27