0

I have strange issue with nullable (I think) types in .net

I simplified my issue to this code:

using System.Linq;

namespace CustomAttribute
{
    class Program
    {
        static void Main(string[] args)
        {
            var person1_firstName_Props = typeof(Person1).GetProperties().Single(x => x.Name == nameof(Person1.FirstName));
            var person2_firstName_Props = typeof(Person2).GetProperties().Single(x => x.Name == nameof(Person2.FirstName));

            var person1_firstName_CustomAttributes = person1_firstName_Props.CustomAttributes;
            var person2_firstName_CustomAttributes = person2_firstName_Props.CustomAttributes;

            // why person2_firstName_CustomAttributes is empty? if we changed nullability of LastName ?
        }
    }

    class Person1
    {
        public string? FirstName { get; set; } = null!;
        public string LastName { get; set; } = null!;
    }

    class Person2
    {
        public string? FirstName { get; set; } = null!;
        public string? LastName { get; set; } = null!;
    }
}

The question is why there is a change related with FirstName field (its properties/attributes) when I change LastName field feature (I added '?' nullable to it). The issue occures in c# 8 and also in earlier versions.

Tom
  • 1
  • im guessing that isn't reflected as thats a compile time concern, not a runtime one. – Daniel A. White Mar 11 '20 at 16:03
  • `var p1 = typeof(Person1).CustomAttributes.Single(x => x.AttributeType.Name == "NullableContextAttribute").ConstructorArguments.Single().Value; // gives 1` – Tom Mar 12 '20 at 09:36
  • `var p2 = typeof(Person2).CustomAttributes.Single(x => x.AttributeType.Name == "NullableContextAttribute").ConstructorArguments.Single().Value; // gives 2` – Tom Mar 12 '20 at 09:36
  • looks like adding more than 50% of nullable string fields to type change attribute (NullableContextAttribute) of this type from 1 to 2 – Tom Mar 12 '20 at 09:39

0 Answers0