webapiclientgen icon indicating copy to clipboard operation
webapiclientgen copied to clipboard

Utilize NotNullAttribute and MayBeNull for HelpStrictMode

Open zijianhuang opened this issue 3 years ago • 3 comments

Currently HelpStrictMode may almost always give a return type an optional null type. However, some APIs always give a proper object / value back. It will be nice that the codegen utilizes NotNullAttribute , and not to give optional null type upon such decoration.

NotNullAttribute https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.notnullattribute?view=net-6.0 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis

zijianhuang avatar Jun 14 '22 12:06 zijianhuang

https://www.meziantou.net/csharp-8-nullable-reference-types.htm very good article.

I am thinking of copying some CodeAnslysis attributes to client codes, but I am not sure if such attributes are available during runtime. Anyway, I can build some local test cases to find out. And https://stackoverflow.com/questions/71144165/notnullattribute-missing-when-checking-by-reflection may apply to .net notnullattribute. https://stackoverflow.com/questions/58453972/how-to-use-net-reflection-to-check-for-nullable-reference-type https://codeblog.jonskeet.uk/2019/02/10/nullableattribute-and-c-8/

However, regarding to class properties, probably RequiredAttribute and DataContract[IsRequired] could be good enough.

zijianhuang avatar Jun 14 '22 21:06 zijianhuang

Option: Support NotNullAttributeOnMethod, SupportNullReferenceOnMethodReturn

If NotNull decorates return

  1. CS Codes will have NotNull copied over.
  2. TS codes will not have null as optional type for return, when HelpStrictMode is true.

When server CS codes return parameter has nullable reference types turned on, System.Runtime.CompilerServices.NullableContextAttribute exists with value 1 or 2 (with question mark).

  1. In CS codes, copy the question marks over.
  2. in TS codes, copy the question mark over, or use null?

zijianhuang avatar Jun 15 '22 04:06 zijianhuang

Both NotNullAttribute and nullable reference types are the concerns of the service programming, checked during compiling or CA. Not all such concerns apply to the client side programming. For example, it is not feasible to copy the constructors dealing with nullable reference types to the client codes. Also, typescripts codes have interfaces for models, not classes, even though other codegen may support client classes.

Currently, in TypeScript client codes, all model properties are optional decorated with a question mark, unless the property is decorated with RequiredAttribute or MemberData(IsRequired=true).

zijianhuang avatar Jun 16 '22 05:06 zijianhuang