Search code examples
c#automappernullability

Making the C# compiler aware that a null-oblivious method may return null?


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.


Solution

  • You can use the MaybeNull attribute.

    The Microsoft documentation uses this example:

    [return: MaybeNull]
    public T Find<T>(IEnumerable<T> sequence, Func<T, bool> predicate)
    

    The preceding code informs callers that the return value may actually be null. It also informs the compiler that the method may return a null expression even though the type is non-nullable.

    From Attributes for null-state static analysis interpreted by the C# compiler


    Obviously, since the type is from an external library, you can only apply the attribute yourself by modifying the external source code.

    You should ask the developers to add the attribute in a future version.