title: C# test if variable assigned
body: <p>I'm trying to code a Linq MinBy extension method</p>
  
  <pre><code>public static class Extensions
  {
      public static T MinBy&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T,int&gt; selector)
      {
          T min;
          int? minKey = null;
          foreach (var x in source)
          {
              var key = selector(x);
              if (minKey == null || key &lt; minKey)
              {
                  minKey = key;
                  min = x;
              }
          }
          if (minKey == null)
          {
              throw new ArgumentException("source should not be empty");
          }
          return min;
      }
  }
  </code></pre>
  
  <p>I think my logic is correct and readable. But I get a build error</p>
  
  <blockquote>
    <p>Use of unassigned local variable 'min'</p>
  </blockquote>
  
  <p>What can I do about this? Can I test if the variable is assigned?</p>
  
  <hr>
  
  <p>Clarification: A MinBy function can answer the following question. Which of the numbers [-5, -2, 3] has the smallest square?</p>
  
  <pre><code>&gt; new List&lt;int&gt;{-5,-2,3}.MinBy(x =&gt; x*x)
  -2
  </code></pre>
  
  <p>.NET's Min function answers a different question (which is the smallest of the squares)</p>
  
  <pre><code>&gt; new List&lt;int&gt;{-5,-2,3}.Min(x =&gt; x*x)
  4
  </code></pre>