3

Currently, I have to convert int to string and store in cache, very complex

int test = 123;
System.Web.HttpContext.Current.Cache.Insert("key", test.ToString()); // to save the cache
test = Int32.Parse(System.Web.HttpContext.Current.Cache.Get("key").ToString()); // to get the cache

Is here a faster way without change type again and again?

Eric Yin
  • 8,737
  • 19
  • 77
  • 118

2 Answers2

6

You can store any kind of object in the cache. The method signature is:

Cache.Insert(string, object)

so, you don't need to convert to string before inserting. You will, however, need to cast when you retrieve from the cache:

int test = 123;
HttpContext.Current.Cache.Insert("key", test); 
object cacheVal = HttpContext.Current.Cache.Get("key");
if(cacheVal != null)
{
    test = (int)cacheVal;
}

This will incur a boxing/unboxing penalty with primitive types, but considerably less so than going via string each time.

spender
  • 117,338
  • 33
  • 229
  • 351
  • `test = (int)HttpContext.Current.Cache.Get("key");` gives error, Cannot convert type `string` to `int`, has to use `Parse`, and to use `Parse`, you have to use `.ToString()` first. – Eric Yin Jan 27 '12 at 01:53
  • 2
    It looks like you didn't store an int in the first place. What is `typeof(HttpContext.Current.Cache.Get("key")).ToString()`? – spender Jan 27 '12 at 01:55
  • you right. But I don't think I can directly do this, since cache maybe `null`, and `(int)null` gives error – Eric Yin Jan 27 '12 at 01:58
1

You could implement your own method that handles it so the calling code looks cleaner.

public void InsertIntIntoCache( string key, int value )
{
   HttpContext.Current.Cache.Insert( key, value );
}

public int GetIntCacheValue( string key )
{
   return (int)HttpContext.Current.Cache[key];
}

int test = 123;
InsertIntIntoCache( "key", test );
test = GetIntCacheValue( "key" );
Brian Dishaw
  • 5,767
  • 34
  • 49