![]() |
|
[C#] [NotNull] attribute for parameters. - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C#] [NotNull] attribute for parameters. (/showthread.php?tid=5318349) |
[NotNull] attribute for parameters. - severos - Jun 26, 2016 I'm writing couple methods that take objects as parameters, currently I'm doing a manual if(obj==null) throw exception/return error. but I've noticed in some built in methods (Encoding.ASCII.GetBytes for example), the parameter have a [NotNull] attribute, any idea how I can get that into my code? tried applying the attribute but can't find it. * - ubbelol - Jun 26, 2016 Not sure about that attribute, but you can do something similar with code contracts: ![]() https://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx * - severos - Jun 26, 2016 (Jun 26, 2016 06:37 AM)ubbelol Wrote: Not sure about that attribute, but you can do something similar with code contracts: A fast reading shows that it's what I want (validate argument isn't null), I'll be taking deeper look at it soon. Thanks for the help :D * - caesay - Jun 30, 2016 The attributes are merely hints to the caller that the method has a certain requirement (NotNull or CanBeNull). Presumably, these attributes assist Microsoft and the CLR team in enforcing code contracts and doing unit tests. In C#6 and roslyn i believe these attributes are internal-only, so they've been deprecated. Some extensions / libraries have their own NotNull attributes - such as Resharper. If you include the JetBrains.Annotations library, you get [notnull] and [canbenull] and many other attributes, and if the consumer of the library has Resharper installed, they will get visual cues if they try to pass in a potential null value as a [NotNull] method parameter. In summary, these attributes are for code contracts, and are not an excuse to skip doing null checks in your methods. |