【问题标题】:Making the C# compiler aware that a null-oblivious method may return null?Making the C# compiler aware that a null-oblivious method may return null?
【发布时间】:2022-12-02 05:52:06
【问题描述】:

AutoMapper's T IMapper.Map<T>(object) is null-oblivious for historical reasons. If you pass null, the result is null. The C# compiler does not warn about the possible null return when returning the result of Map from a method declared to return T.

Is there a way to make the compiler treat Map as if it had been declared as T? IMapper.Map<T>(object?)? I thought about wrapping IMapper in a different interface and injecting that instead, but that seems a bit heavy-handed.

【问题讨论】:

    标签: c# automapper nullability


    【解决方案1】:

    Firstly, object? is incorrect, as object is reference type and can accept null. Secondly, if generic parameter T is reference type, all good. And if it's value type — why don't you specify, for example, IMapper.Map<int?> instead of IMapper.Map<int>?

    If for some reason you can't do that, you can cast a value type to its nullable twin:

    object obj;
    IMapper mapper;
    // Initialize obj and mapper
    
    var result = (int?)mapper.Map<int>(obj);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2021-05-16
      • 1970-01-01
      • 2020-07-11
      • 2019-12-05
      相关资源
      最近更新 更多