ReSharper: how to remove “Possible 'System.NullReferenceException'” warning

后端 未结 6 1947
长情又很酷
长情又很酷 2020-12-11 02:41

Here is a piece of code:

IUser user = managerUser.GetUserById(UserId);
if ( user==null ) 
    throw new Exception(...);

Quote quote = new Quote(user.FullNam         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-11 03:39

    You do know (or expect) that this code will throw an exception if there is a null reference:

    ComponentException.FailIfTrue([...]);
    

    However, since there is no contract specifying this, ReSharper has to assume that this is just a normal method call which may return without throwing any exception in any case.

    Make this method implement the ReSharper contract, or as a simple workaround (which only affects debug mode, therefore no performance penalty for release mode), just after the FailIfTrue call:

    Debug.Assert(user != null);
    

    That will get rid of the warning, and as an added bonus do a runtime check in debug mode to ensure that the condition assumed by you after calling FailIfTrue is indeed met.

提交回复
热议问题