Throwing ArgumentNullException

前端 未结 12 2178
名媛妹妹
名媛妹妹 2020-12-08 02:10

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it\'s a fatal error and an exception shoul

12条回答
  •  醉梦人生
    2020-12-08 02:12

    I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object.

    If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.

    If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it.

提交回复
热议问题