0

I have the following piece of c# code:

myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;

CodeContract knows that myClaimsIdentity is never null. But it complains that the FindFirst(string) method might return null:

Warning CodeContracts: Possibly calling a method on a null reference. Do you expect that System.Security.Claims.ClaimsIdentity.FindFirst(System.String) returns non-null?

I do expect this, but how can I tell it to the CodeChecker? Of course I can't change the the FindFirst(string) since it comes from an external library.

Rufus Buschart
  • 362
  • 1
  • 13

1 Answers1

2

The simple approach is:

var nameIdentifier = myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
Contract.Assume(nameIdentifier != null);
nameIdentifier.Value;

Code contracts will not try to prove the Assume condition, but will use it when proving other requirements.

It's probably possible to create a contract reference assembly for the external code which has the appropriate Ensures post-conditions. The code contracts team does this for the BCL types. But I don't know how to do that.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 1
    But putting such a thing in a contract assembly would be *horribly* wrong. [`ClaimsIdentity.FindFirst`](https://msdn.microsoft.com/en-us/library/hh159719%28v=vs.110%29.aspx) *can* return `null`, and the documentation spells it out: "or **null** if no match is found." But in a specific application, for a specific claim type, you may know that it won't return `null`. `Contract.Assume` is the right tool for the job here. –  May 12 '15 at 07:24
  • @hvd I'm not familiar with that library, so I don't know under which circumstances it can return null. If `ClaimTypes.NameIdentifier` always exists one could write `Contract.Ensures(type != ClaimTypes.NameIdentifier || result != null)`. If the OP only knows that it's not null because the value will always be set *in their application*, then `Contract.Assume` is the correct approach. – CodesInChaos May 12 '15 at 07:28
  • You are absolutely right - I should do this check here to be on the safe site. – Rufus Buschart May 12 '15 at 08:04