Home > database >  Cannot convert source type T? to target type T?
Cannot convert source type T? to target type T?

Time:03-14

I want to create simple cache manager (for Redis) who return value genereic type T but when i deserialize value from Redis i got error cannot convert source type T? to target type T?

public class InMemoryCacheService<T> : ICacheService<T>
{
   private T? cacheValue = default(T?);

   public async Task<T> GetValueAsync<T>(string key, Expression<T> expression)
   {
       
      GetCacheGalueAsync<T>(key);

      //code where I check if cacheValue is null get value from DB
   }


   public void GetCacheGalueAsync<T>(string key) 
   {
      string value = _distributedCache.GetString(key);
      if (value is not null)
      {
         T? t = JsonSerializer.Deserialize<T>(value);

         //cannot convert source type T? to target type T?
         cacheValue = t;
      }
   }
}


CodePudding user response:

There are two different type parameters called T here. One is in the generic type declaration:

public class InMemoryCacheService<T>

The other is in the generic method declaration:

public void GetCacheGalueAsync<T>(string key)

If you rename these respectively to TClass and TMethod, you'll see a different error message, converting TMethod? to TClass?.

I strongly suspect you just want to make your method non-generic:

public void GetCacheValueAsync(string key)

That way T will just refer to the type parameter declared by the class.

  • Related