Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using [NotNull] for a method's parameters

Tags:

c#

Consider this code from ASP.NET MVC's source code:

public static IApplicationBuilder UseMvc(             [NotNull] this IApplicationBuilder app,             [NotNull] Action<IRouteBuilder> configureRoutes) {...} 

According to this answer, the annotated parameters must not be null. Then why can I pass null to the method? That is, in the case below, why doesn't the compiler give me any error?

app.UseMvc(null); 
like image 265
Sirwan Afifi Avatar asked Sep 27 '15 09:09

Sirwan Afifi


People also ask

What does NotNull annotation do?

@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.

Should you use @NotNull?

A method should not return null Variables (fields, local variables, and parameters) cannot hold a null value. For example, if you create a method where a parameter has the @NotNull annotation, and then call this method with a parameter that potentially can be null , IntelliJ IDEA will highlight the problem on the fly.

What does javax validation constraints NotNull do?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.

What is the use of @nullable annotation?

The @NonNull/@Nullable annotation can put in front of functions as well to indicate the return value nullability. return null; // warn: 'null' is returned by the method ... Easy, right? Keep your Billion Dollar in your pocket and enjoy using this @Nullable and @NonNull.


1 Answers

The only attribute that can cause the compiler to generate an error is the ObsoleteAttribute. It is because this attribute's behavior is hard-coded into the compiler.

Attributes like the NotNull attribute are generally meant for tools (like ReSharper) to generate warnings or errors while writing code. Please read about this particular attribute here.

You can also use tools like PostSharp to issue additional build-time errors.

like image 51
Dmytro Shevchenko Avatar answered Oct 01 '22 12:10

Dmytro Shevchenko