trampster
trampster

Reputation: 8918

How to check if nullable reference types are on in a .net 5 Source Generator

I'm making a .Net 5 Source Generator based json library.

I can optimise string handling by skipping null checks on parsing json string properties if I know they can't be null.

With Nullable Reference Types on I can assume string (without ?) isn't null. However if Nullable References types is off I can't.

How can I determine from the .Net 5 Source Generator if Nullable Reference Types are on or not.

Upvotes: 2

Views: 954

Answers (1)

Jason Malinowski
Jason Malinowski

Reputation: 19021

Because of the #nullable directive it's possible for it to be on or off at different places. What you should do is look at the ITypeSymbol for whatever symbol you're looking at, as that will have a NullableAnnotation property which is this enum. 'None' in that case means "the feature wasn't enabled for that type", and Annotated/NotAnnotated means the feature is enabled and that's the the appropriate state. So in your case, if ITypeSymbol.NullableAnnotation is "NotAnnotated" that means it's a non-nullable type.

Upvotes: 3

Related Questions