user3346290
user3346290

Reputation: 53

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); }}}

Upvotes: 3

Views: 6468

Answers (2)

Friyank
Friyank

Reputation: 479

you can try this

  private string _code="";


public string Code
{
    get
    {  return _code ; } 

    set 
    {
       _code = value ?? "";
    }
}

Upvotes: 2

Timwi
Timwi

Reputation: 66573

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;
    }
}

Upvotes: 8

Related Questions