ASP.NET cache add vs insert

asp.netCaching

asp.net Problem Overview


What is the difference between the Cache.Add() and Cache.Insert() methods?

In which situations should I use each one?

asp.net Solutions


Solution 1 - asp.net

Insert will overwrite an existing cached value with the same Key; Add fails (does nothing) if there is an existing cached value with the same key. So there's a case for saying you should always use Insert since the first time the code runs it will put your object into the cache and when it runs subsequently it will update the cached value.

Solution 2 - asp.net

Cache.Add() also returns a cached object from Cache after it was added:

string cachedItem = Cache.Add("cachedItem", ....);

Solution 3 - asp.net

You can use either Cache.Add() or Cache.Insert() methods for caching your data. The only difference between the two is, Cache.Add() method returns the object which you want to cache. So let’s say if you want to use the object and cache it as well. You can do so in a single line of code with the help of Cache.Add().

Cache.Insert() methods has 4 different types of overloaded methods while Cache.Add() has only one.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionguchko-glebView Question on Stackoverflow
Solution 1 - asp.netPhilPursgloveView Answer on Stackoverflow
Solution 2 - asp.netArtem GView Answer on Stackoverflow
Solution 3 - asp.netSHEKHAR SHETEView Answer on Stackoverflow