简体   繁体   中英

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

Don't use a List<string> for uniqueness-checking. It will become less efficient as the list will grow. Consider using a HashSet<string> for that.

class City
{
    private readonly HashSet<string> _companyNames = new HashSet<string>();

    public ICompany AddCompany(string name)
    {
        // check 'name' for null here ...
        // ...

        // 'Add' will return 'false' if the hashset already holds such a string
        if (!_companyNames.Add(name))
        {
            throw new ArgumentException("Such a company already exists in this city");
        }

        // ... your code
    }
}

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

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