c# : HttpRuntime.Cache produces invalid cast exception

873 views Asked by At

How can the following produce an "invalid cast exception" ???

foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)
{
    if (entry.Value.GetType() == typeof(MyClass))
    {
        MyClass mc = (MyClass)entry.Value; // ===> Invalid Cast Exception !!!

(To those who are asking why I want to do this : I randomly add and remove a few different objects in/from the cache so the need for this kind of test. I was planning to create some sort of container object that would hold my various objects; I would push only this object in the cache but the question remains : would it solve the cast exception ?)

3

There are 3 answers

0
user1409737 On BEST ANSWER

OK I finally made it.

First of all, my apologies, I was erroneously reading my log file. The exception did not come form

MyClass mc = (MyClass)entry.Value;

but from

foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)

It appears the Cache can't be iterated with a KeyValuePair (a code I had found on the internet...). Once again, sorry for wasting your time searching in a wrong direction... Thanks for your help anyway !

And now for the code that works :

IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
    while (CacheEnum.MoveNext()) {
        MyClass mc = ((DictionaryEntry)CacheEnum.Current).Value as MyClass;
        if (mc != null) {
            // Doing stuff...
0
skarmats On

Are you in an environment that does dynamic (re-)compilation? ASP.NET Websites, for example, recompile pages at runtime if the code file changes. They will compile that page to an assembly and load that assembly. Even if the runtime unloads the old assembly at some point, this still gives you a new type that is not compatible with the old one.

I don't know, if you can work around this with some kind of versioning or strong naming. But since the change occured, it seems unlikely, you'd want the old type around.

3
Peter On

No idea why your code fails, but you can try this with a 'softcast':

foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache) 
{ 
     MyClass mc = entry.Value as MyClass;
     if (mc != null)     
     {         
          //Do your stuff