Renato de A. Renato de A. - 2 months ago 5
C# Question

Passing new instance of custom type to List.Add() method call

I have an Item class that inherits from IEquatable:

class Item : IEquatable<Item>
{
public string item;

public Item(string name)
{
this.item = name;
}

public bool Equals(Item other)
{
if (other == null) return false;
return (this.item.Equals(other.item));
}
}


However, creating a list of that type and attempting to load that list with a new instance of the type will result in a NullReferenceException:

static void Method()
{
List<Item> itemList = new List<Item>();
string itemToAdd = Console.ReadLine();
itemList.Add(new Item(itemToAdd));
}


What am I not initializing?

Answer

The error is originating from the fact that item has a null value and you do not account for that in your Equals implementation. this.item.Equals will throw an NRE if item has a null value when it is called.

  1. You should gaurd against null values in your types where there should be none. Validate all input as soon as possible in the call stack.
  2. Never expose fields directly from a type! If you want to expose it use a Property and if you expose the set of the property validate the input!

Code with gaurds:

class Item : IEquatable<Item>
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            if (value == null)
                throw new ArgumentNullException("value");
            _name = value;
        }
    }

    public Item(string name)
    {
        if (name == null)
            throw new ArgumentNullException("name");
        this._name = name;
    }

    public bool Equals(Item other)
    {
        if (other == null) return false;
        return string.Equals(this.Name, other.Name);
    }
}
Comments