Why is casting to a type in this way not valid syntax?
<p>The compiler complains on "as typeOfState" saying that typeOfState could not be found. Why is this? Is there a way to express what I am trying to accomplish?</p>

<pre><code>public static readonly IDictionary&lt;Type, string&gt; StateDictionary = new Dictionary&lt;Type, string&gt;
{
    {typeof(SerializableDictionary&lt;string, RadTabSetting&gt;), "TabStates"},
    {typeof(SerializableDictionary&lt;string, RadPaneSetting&gt;), "PaneStates"},
    {typeof(SerializableDictionary&lt;string, RadDockSetting&gt;), "DockStates"},
    {typeof(SerializableDictionary&lt;string, RadDockZoneSetting&gt;), "DockZoneStates"},
    {typeof(SerializableDictionary&lt;string, RadSplitterSetting&gt;), "SplitterStates"},
    {typeof(SerializableDictionary&lt;string, RadSplitBarSetting&gt;), "SplitBarStates"},
    {typeof(SerializableDictionary&lt;string, RadPageViewSetting&gt;), "RadPageViewStates"},
    {typeof(GlobalSettings), "GlobalSettings"},
};

foreach (var item in StateManager.StateDictionary)
{
    string stateName = item.Value;
    Type typeOfState = item.Key;

    object stateSession = SessionRepository.Instance.GetSession(stateName) as typeOfState;

    dataToSave.Add(stateName, stateSession);
}
</code></pre>

<p>Cheers</p>

<p>EDIT: Okay. Understood that cannot use a variable as a type, even if the variable is of type "Type"</p>

<p>What are my options? Here's full source:</p>

<pre><code>[WebMethod]
public static bool Export()
{
    bool successful = false;

    try
    {
        HttpContext.Current.Request.ContentType = "text/xml";
        HttpContext.Current.Response.Clear();

        SerializableDictionary&lt;string, object&gt; dataToSave = new SerializableDictionary&lt;string, object&gt;();

        foreach (var item in StateManager.StateDictionary)
        {
            string stateName = item.Value;
            Type typeOfState = item.Key;

            object stateSession = SessionRepository.Instance.GetSession(stateName);

            dataToSave.Add(stateName, stateSession);
        }

        XmlSerializer serializer = new XmlSerializer(dataToSave.GetType());
        serializer.Serialize(HttpContext.Current.Response.OutputStream, dataToSave);

        successful = true;
    }
    catch (Exception exception)
    {
        _logger.ErrorFormat("Unable to serialize session. Reason: {0}", exception.Message);
    }

    return successful;
}
</code></pre>
