Search code examples
c#listexceptionarraylistargumentexception

How can we throw exception for List<string> in C# with used interfaces and constructs?


I need to call throw ArgumentException on the list which stores name of company (name can exist once in current city) inside of a class City. How can I create a list of names and throw the exception if I have a list of names?

class City : ICity
{
    private List<string> _companyNames;
    internal City(string name)
    {
        this.Name = name;
        _companyNames = new List<string>();
    }
    public string Name
    {
         get;  
    }

    public ICompany AddCompany(string name)
    {

        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentNullException("invalid name");
        }

        //create a list and check if exist
        List<string> _companyNames = new List<string>() {name, name, name};
        //public bool Exists(Predicate<T> match);
        //Equals(name) or sequennceEqual
        if (!_companyNames.Equals(obj: name))
        {
            throw new ArgumentException("name already used");
        }


        return new Company(name, this);
    }
}

Solution

  • If you want the Add itself to throw the exception, one thing you could do is to create your own implementation. Something like the following:

    public class MyList<T> : List<T>
    {
        public new void Add(T item)
        {
            if (Contains(item))
            {
                throw new ArgumentException("Item already exists");
            }
            base.Add(item);
        }
    }