usually we have the:
public string code { get; set; }
I need to avoid null reference exception if eventually someone sets code to null
I try this idea ... any help?
public string code { get { } set { if (code == null) { code = default(string); }}}
You need to declare a backing field, which I’ll call _code here:
private string _code = "";
public string Code
{
get
{
return _code;
}
set
{
if (value == null)
_code = "";
else
_code = value;
}
}
I’ve also renamed the property to Code because it is customary in C# to capitalise everything that’s public.
Note that in your own code, you wrote default(string), but this is the same as null.
Instead of setting _code to "", it is common practice to throw an exception:
private string _code = "";
public string Code
{
get
{
return _code;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
_code = value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With