Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a typed value to generic type T?

Tags:

c#

generics

I'm trying to use Azure Redis Cache in .NET Core application. I have written a CacheHelper generic method which implements generic interface like below.

However this issue is more related to Generics.

I'm getting error while casting cache value to generic type. Is this the correct way to do? or Am i missing something? Please see the code below.

public class CacheHelper<T> : ICacheHelper<T>
{
    private ICacheProvider _cacheProvider;

    public CacheHelper(ICacheProvider cacheProvider)
    {
        _cacheProvider = cacheProvider;
    }

    public async Task<CacheResponse<T>> GetCacheValueAsync(string key)
    {
        RedisValue value = await _cacheProvider.GetCacheDatabase().StringGetAsync(key);
        if (typeof(T).Equals(typeof(string)))
        {
            return value.HasValue
            ? new CacheResponse<T>(value) //I'm getting error here cannot cast type RedisValue to type T
            : CacheResponse<T>.NoValue();
        }
        else
        {
            T obj = JsonConvert.DeserializeObject<T>(value);
            return value.HasValue
           ? new CacheResponse<T>(obj)
           : CacheResponse<T>.NoValue();
        }
    }
}
like image 863
PNDev Avatar asked Oct 22 '25 01:10

PNDev


1 Answers

You could use the built-in Convert class to your advantage here:

new CacheResponse<T>((T)Convert.ChangeType(value, typeof(T));
like image 164
Martin Zikmund Avatar answered Oct 23 '25 17:10

Martin Zikmund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!