0

I have a question about a code snippet in my application. x.UsesFeature and Person.UsesFeature are both of type optional bool (bool?). When src.Person.UsesFeature = null, the right side of the ternary operator will be evaulated. My understanding is that the default value of bool? is null. But when this is done mapping, x.UsesFeature is set to False, not null. Why is this happening?

                var config = new MapperConfiguration(cfg => cfg.AddProfile<TestProfile>());

. . .then when I map the property in that TestProfile class

   .ForMember(x => x.UsesFeature, opt =>
            {
                opt.MapFrom(src => src.User.UsesFeature.HasValue ? src.User.UsesFeature.Value : default);
            })
Nick Heiting
  • 75
  • 10
  • Please provde a [mre] that replicates your problem. See https://stackoverflow.com/questions/3083654/automapper-null-properties and https://stackoverflow.com/questions/38237908/automapper-checking-for-null-in-mapfrom – Patrick Artner Nov 04 '20 at 17:58
  • Check [the execution plan](https://docs.automapper.org/en/latest/Understanding-your-mapping.html). – Lucian Bargaoanu Nov 04 '20 at 19:25

1 Answers1

1

It's not an Automapper problem, if you do the below, you'll see that it sets to false:

bool? foo = null;
var bar = foo.HasValue ? foo.Value : default;

However, simply changing the default to default(bool?) resolves your issue.

bool? foo = null;
var bar = foo.HasValue ? foo.Value : default(bool?);
gilliduck
  • 2,762
  • 2
  • 16
  • 32
  • This seems to be [confirmed as a bug](https://stackoverflow.com/a/46997896/3034273) in C# 7.1 and later fixed in 7.2. – Xerillio Nov 04 '20 at 21:04