0

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);
    }
1
  • 2
    AgentId is null in scrubAgentId's char[] arr = this.AgentId.ToCharArray(); Commented Apr 26, 2013 at 17:49

4 Answers 4

6

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

0

Are you initialising agentid anywhere first?

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

Comments

0

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

2 Comments

This will throw an exception if a caller attempts to set AgentId=null;
Obviously. You might notice the 'something like this' qualification. How to handle the edge case there should be pretty obvious (and dependent on the desired semantics of the property).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.