title: When Condition Method in Moq
body: <p>I am trying to figure how to use When method for my use. </p>
  
  <pre><code>When(Func&lt;bool&gt; condition);
  </code></pre>
  
  <p>Another post here has one example of usa of When method</p>
  
  <pre><code>var mockedService = new Mock&lt;IFormatProvider&gt;();
  
  mockedService.When(() =&gt; DateTime.Now.Hour &lt; 12).Setup(x =&gt; x.GetFormat(typeof(string))).Returns(null);
  </code></pre>
  
  <p>What I am trying to do is I have a variable called x. I want to use When method so it performs action only when X is not Null.</p>
  
  <p>for example</p>
  
  <pre><code>      mockedService.When(()=&gt; !null x).Returns(x)
        or
        mockedService.When(condition =&gt; x).Returns(x);
  </code></pre>
  
  <p>Both of the above lines of code are not working syntex is not correct. 
  Any idea how to write it correctly. Thanks </p>