Design by contract/C# 4.0/avoiding ArgumentNullException

╄→尐↘猪︶ㄣ 提交于 2019-11-29 14:58:31

问题


I'm terribly tired of checking all my arguments for null, and throwing ArgumenutNullExceptions when they are.

As I understand it, C# 4.0 enables some design by contract constructs. Will it be possible to specify that a method will not accept null arguments in C# 4.0?

Also, is there anything I can do in the meantime (maybe an attribute?) to avoid this monotonous task of checking for null and throwing?


回答1:


You can create a NotNull<T> generic class that helps, but there are some side effects. See Robert Nystrom's blog post.




回答2:


Rick Brewster describes a good solution for concise, declarative style parameter checking in this post,

http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/

Avoids use of reflection (drawback of DbC) and creates no overhead for non-exceptional code path.

Like how he uses extension methods to allow what appears to be instance method calls on null objects. Very clever bit of coding IMO.

If you are sold on DbC, Google Spec# and PostSharp.




回答3:


Not sure about native DbC constructs in C# 4.0 but Microsoft is going to release cross-language Contracts library.
You can download version for MSVS2008 here.




回答4:


As an alternative to the already given answers, it is worth looking into the Null Object design pattern.

The essence of this design pattern is that once the "null object" is created, there is no further need to perform any checks for null and the methods of the null object implement the behavior desired whenever a null (otherwise) would have been passed vs a reference to a "real object".

This design pattern does not depend on C# 4.0 and in fact can be easily implemented in almost any OO programming language.




回答5:


I have just started using Code Contracts its a new feature in C# 4.0 you need to download an addin from MS to allow you to see it in your project settings. Details here -> http://research.microsoft.com/en-us/projects/contracts/



来源:https://stackoverflow.com/questions/434088/design-by-contract-c-4-0-avoiding-argumentnullexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!