NealR
NealR

Reputation: 10699

C# NullReferenceException in class validation method

I am trying to add a helper method to scrub out any non-alphanumeric characters in my class. However, I keep getting the error

NullReferenceException: Object reference not set to an instance of an object.   

Not sure what I'm doing wrong here since I thought this was the proper way to set up any kind of validation within a class. Any suggestions would be appreciated.

    private string agentId;
    public string AgentId
    {
        get { return agentId; }
        set { agentId = this.scrubAgentId(); } 
    }

    private string scrubAgentId()
    {
        char[] arr = this.AgentId.ToCharArray();

        arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c))));
        return new string(arr);
    }

Upvotes: 0

Views: 147

Answers (4)

Nicholas Carey
Nicholas Carey

Reputation: 74287

You never reference the value in your setter. You want to do something like this:

private string agentId;
public string AgentId
{
    get
    {
      return agentId ;
    }
    set
    {
      agentId = new string( value.ToCharArray().Where( c => c.IsLetterOrDigit(c) ) ) ;
    }
}

Upvotes: 0

Kyle
Kyle

Reputation: 1011

Are you initialising agentid anywhere first?

Its failing on char[] arr = this.AgentId.ToCharArray();

Upvotes: 0

bash.d
bash.d

Reputation: 13207

In the set part of the property you have an implicit object, value which holds the value you want to set... Use this value as your base

private string agentId;
public string AgentId
{
    get { return agentId; }
    set { agentId = value; } // manipulate value here using your method
}

Upvotes: 0

Jordan Kaye
Jordan Kaye

Reputation: 2887

This isn't really right at all. You're discarding the value when performing your set. It should probably look something more like this:

    private string agentId;
    public string AgentId
    {
        get { return agentId; }
        set { agentId = this.scrubAgentId(value); } 
    }

    private string scrubAgentId(string value)
    {
        if(value == null)
            return value;
        char[] arr = value.ToCharArray();

        arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c))));
        return new string(arr);
    }

Upvotes: 6

Related Questions