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?
public static readonly IDictionary<Type, string> StateDictionary = new Dictionary<Type, string>
{
{typeof(SerializableDictionary<string, RadTabSetting>), "TabStates"},
{typeof(SerializableDictionary<string, RadPaneSetting>), "PaneStates"},
{typeof(SerializableDictionary<string, RadDockSetting>), "DockStates"},
{typeof(SerializableDictionary<string, RadDockZoneSetting>), "DockZoneStates"},
{typeof(SerializableDictionary<string, RadSplitterSetting>), "SplitterStates"},
{typeof(SerializableDictionary<string, RadSplitBarSetting>), "SplitBarStates"},
{typeof(SerializableDictionary<string, RadPageViewSetting>), "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);
}
Cheers
EDIT: Okay. Understood that cannot use a variable as a type, even if the variable is of type “Type”
What are my options? Here’s full source:
[WebMethod]
public static bool Export()
{
bool successful = false;
try
{
HttpContext.Current.Request.ContentType = "text/xml";
HttpContext.Current.Response.Clear();
SerializableDictionary<string, object> dataToSave = new SerializableDictionary<string, object>();
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;
}
You cannot use a
Typeobject with theaskeyword. Check the documentation for its proper usage.To accomplish what I think you’re trying to do, perhaps look into
Convert.ChangeType[MSDN].