Mark parameters as NOT nullable in C#/.NET?

后端 未结 6 2024
粉色の甜心
粉色の甜心 2020-12-02 21:53

Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET? Ideally this would also

6条回答
  •  广开言路
    2020-12-02 22:26

    There's nothing available at compile-time, unfortunately.

    I have a bit of a hacky solution which I posted on my blog recently, which uses a new struct and conversions.

    In .NET 4.0 with the Code Contracts stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.

    I also have an extension method in MiscUtil called ThrowIfNull which makes it a bit simpler.

    One final point - any reason for using "if (null == arg)" instead of "if (arg == null)"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.

提交回复
热议问题