Search code examples
c#genericscachinggeneric-method

Generic Method always returning NULL


I have a generic method (already developed by another developer way back) in my project for fetching cache; though I have values for the key the method still returns NULL.

Please take a look on the code:

public static C GetFromCache<C>(string key) where C : class     
    {     
       if (cache != null)
       {
          var testCache = cache.Get(key); // This variable is getting results
          C p = cache.Get(key) as C; this point value of 'p' is NULL
          return p; 
        }

        return null;
    }

method call:

var lstCheck = ClassName.GetFromCache< List< int >(key);

Debugger screenshot


Solution

  • This happens because the result of cache.Get(key) isn't a C type. Let me explain with code:

    Object name = "my-name";
    var nameAsString = name as String; // name is already a String, so nameAsString = "my-name"
    var nameAsRandom = name as Random; // name isn't Random, so nameAsRandom == null 
    

    Best,