How do I implement a data cache in C#

Implementing a data cache in C# can significantly improve the performance of your applications by reducing the number of times data needs to be fetched from a slower data store, such as a database or an external API. This example will demonstrate a simple in-memory caching mechanism using the MemoryCache class from the System.Runtime.Caching namespace.

Example of a Simple Data Cache

using System; using System.Runtime.Caching; public class DataCache { private MemoryCache _cache; public DataCache() { _cache = MemoryCache.Default; } public T GetData(string key, Func fetchFunc, DateTimeOffset? absoluteExpiration = null) { if (_cache.Contains(key)) { return (T)_cache.Get(key); } var data = fetchFunc(); _cache.Add(key, data, absoluteExpiration ?? DateTimeOffset.Now.AddMinutes(10)); return data; } public void Remove(string key) { _cache.Remove(key); } } // Usage Example: // var dataCache = new DataCache(); // var data = dataCache.GetData("myKey", () => FetchFromDataSource());

data cache C# in-memory cache MemoryCache application performance