Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET can't cache null value

Tags:

Can anyone explain why you cannot insert a null object into the ASP.NET cache?

string exampleItem = null;  HttpRuntime.Cache.Insert("EXAMPLE_KEY",                          exampleItem,                          Nothing,                                                    DateTime.Now.AddHours(1),                         System.Web.Caching.Cache.NoSlidingExpiration); 

The exception error message states that the "value" object cannot be null. In my application there are valid reasons why we whould want to store a null value in the cache.

like image 401
Kane Avatar asked Jun 09 '09 02:06

Kane


1 Answers

Underlying Cache is likely a Hashtable or Dictionary<string, object>, whose getters do not differentiate between no value at that key, or a null value at that key.

Hashtable table = new Hashtable(); object x = table["foo"]; table.Add("foo", null); object y = table["foo"]; Console.WriteLine(x == y); // prints 'True' 

Consider a using placeholder "null" item, similar to DbNull.Value.

like image 122
Michael Petrotta Avatar answered Oct 04 '22 15:10

Michael Petrotta