Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct .NET exception to throw when try to insert a duplicate object into a collection?

I have an Asset object that has a property AssignedSoftware, which is a collection.

I want to make sure that the same piece of Software is not assigned to an Asset more than once. In Add method I check to see if the Software already exist, and if it does, I want to throw an exception.

Is there a standard .NET exception that I should be throwing? Or does best practices dictate I create my own custom exception?

like image 386
mattruma Avatar asked Sep 10 '08 17:09

mattruma


1 Answers

Why has InvalidOperationException been accepted as the answer?! It should be an ArgumentException?!

InvalidOperationException should be used if the object having the method/property called against it is not able to cope with the request due to uninit'ed state etc. The problem here is not the object being Added to, but the object being passed to the object (it's a dupe). Think about it, if this Add call never took place, would the object still function as normal, YES!

This should be an ArgumentException.

like image 162
Rob Cooper Avatar answered Oct 13 '22 01:10

Rob Cooper