foreach not initialising the loop variable
<p>I'm using a foreach to loop through an IList of objects in a Partial View in ASP.NET MVC.</p>

<p>Here's the entire code (Message is one of my classes from the Model).</p>

<pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;IList&lt;Message&gt;&gt;" %&gt;

&lt;%
if (ViewData.Model.Count &gt; 0)
{
    foreach (MvcTest.Models.Message m in ViewData.Model)
    {
        Response.Write(m.RenderHtml()); 
    }
}

%&gt;
</code></pre>

<p>For some reason, this generates a CS0165 on the ResponseWrite - complaining that m may not be initialised.</p>

<p>I rewrote it like this:</p>

<pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;IList&lt;Message&gt;&gt;" %&gt;

&lt;%
//Can't see why I have to declare this as a variable, but I get CS0165 if I use ViewData.Model directly in the foreach
IList&lt;MvcTest.Models.Message&gt; messages = ViewData.Model;
if (messages.Count &gt; 0)
{
    foreach (MvcTest.Models.Message m in messages)
    {
        Response.Write(m.RenderHtml()); 
    }
}

%&gt;
</code></pre>

<p>ie explicitly declaring a variable for the IList rather than just using the (strongly-typed) Model, and it works fine.</p>

<p>Can anyone explain why what I did fixes the problem?</p>
