Question Details

No question body available.

Tags

c# nullable

Answers (4)

February 25, 2026 Score: 8 Rep: 30,850 Quality: Medium Completeness: 40%

MemberNotNullWhenAttribute is a public attribute, but you used it wrong. It should annotate the HasValue property and specify the name of the X property:

[MemberNotNullWhen(true, nameof(X))] public bool HasValue { get => Position.HasValue; }
February 25, 2026 Score: 1 Rep: 111,201 Quality: Low Completeness: 50%

This works for me:

using System;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;

namespace ConsoleApp1;

public static class Program { static void Main() { position = new Vector3(1, 2, 3); Console.WriteLine(test()); }

static Vector3 test() { if (!HasValue) return new Vector3();

return X.Value; }

[MemberNotNullWhen(true, nameof(X))] // Comment this line out to see the difference. public static bool HasValue =>
position.HasValue;

static Vector3? X => position;

static Vector3?
position; }
February 25, 2026 Score: 1 Rep: 5,499 Quality: Low Completeness: 50%

MemberNotNullWhenAttribute is generally public. If you saw it internal somewhere, that's most likely what is called a "polyfill". The attribute is publicly available on .NET 5+ and later, but people can create their own definition on .NET Standard or .NET Framework, and the compiler will still consider it. Your own definition can be internal (and even preferrable with EmbeddedAttribute to avoid issues with InternalsVisibleTo).

To answer the original question, you need to add the attribute on HasValue as follows:

    [MemberNotNullWhen(true, nameof(Position))]
    [MemberNotNullWhen(true, nameof(X))]
    [MemberNotNullWhen(true, nameof(Y))]

That way, you won't get warnings whenever you access Position, X, or Y, in a code path where HasValue is statically determined by the compiler to be true.

February 25, 2026 Score: 0 Rep: 1 Quality: Low Completeness: 40%

Wouldn’t a simply checking before that with this work?

if(X!.HasValue || Y!.HasValue) return null

if (!HasValue) return null; return new Vector3(0.5f (X!.Value - Y!.Value), 0.25f (X!.Value + Y!.Value) + 0.25f, 0.0f);