Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate the setter to avoid null

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); }}}
like image 922
user3346290 Avatar asked Aug 11 '26 13:08

user3346290


1 Answers

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;
    }
}
like image 140
Timwi Avatar answered Aug 13 '26 04:08

Timwi