简体   繁体   中英

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

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

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
}

Are you initialising agentid anywhere first?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM