mbabramo
mbabramo

Reputation: 2843

Find Roslyn default nullable context

We can use Roslyn (Microsoft CodeAnalysis) to get the nullability context. But the NullableContext struct often indicates that the nullable context is inherited from the project default. In an analyzer, I thus need to determine the project default nullable context. I have not figured out a way to do this from the compilation object or the semantic model.

Is there some way to do this?

Upvotes: 3

Views: 347

Answers (2)

Jason Malinowski
Jason Malinowski

Reputation: 19021

If you want the project default, you can get it from Compilation.Options.NullableContextOption.

But as you correctly observed in your answer, asking the semantic model computes the effective value for you.

Upvotes: 2

mbabramo
mbabramo

Reputation: 2843

I may have posted this prematurely, as I found a solution shortly after posting. The answer is that when NullableContext is set to Inherited, that is a flags value where the flag for warnings enabled is not set, so a context supporting non-nullable reference types is not enabled (that is, we have old style code). So, at least i don't need to figure out what the project default is.

More generally, one can test the flags as follows:

public static class NullableContextExtensions
    {
        private static bool IsFlagSet(NullableContext context, NullableContext flag) =>
            (context & flag) == flag;

        public static bool WarningsEnabled(this NullableContext context) =>
            IsFlagSet(context, NullableContext.WarningsEnabled);

        public static bool AnnotationsEnabled(this NullableContext context) =>
            IsFlagSet(context, NullableContext.AnnotationsEnabled);
    }

On the other hand, one might still want to know the project default, so if anyone posts the code for achieving that, I will mark it as the correct anwer.

Upvotes: 1

Related Questions