Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning null from C# generic regardless of supplied type
    primarykey
    data
    text
    <p>I'm writing an in-memory cache of settings for our webservices. This is so that we do not have to hit the database every time we need a setting. We have a mechanism to invalidate the cache when the database is updated.</p> <p>The cache is a bunch of dictionaries that contain different types, here's two of those dictionaries:</p> <pre><code>static readonly object StringValueCacheMutex = new object(); static readonly Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; StringValueCache = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;(); static readonly object IntegerValueCacheMutex = new object(); static readonly Dictionary&lt;string, Dictionary&lt;string, Int64&gt;&gt; IntegerValueCache = new Dictionary&lt;string, Dictionary&lt;string, Int64&gt;&gt;(); </code></pre> <p>I would like to write a generic function that gets a value from these dictionaries, if the category/setting was not found in the dictionary it should return null to signify it was not found. </p> <p>The problem is that these dictionaries contain both nullable and non-nullable types.</p> <p>Here's the generic I want to have:</p> <pre><code>public static TValue GetValueOrNull&lt;TValue&gt;( IDictionary&lt;string, Dictionary&lt;string, TValue&gt;&gt; cacheDictionary, object cacheMutex, string categoryName, string settingName) { TValue value = null; lock (cacheMutex) { if (cacheDictionary.ContainsKey(categoryName)) { if (cacheDictionary[categoryName].ContainsKey(settingName)) { value = cacheDictionary[categoryName][settingName]; } } } return value; } </code></pre> <p>This will not compile due to : "Cannot convert null to type parameter 'TValue' because it could be a non-nullable value type. Consider using 'default(TValue)' instead."</p> <p>The reason I want to return null and not default(TValue) is that in the case of an integer, the caller has no way of knowing if the setting value was actually 0 or of it was not found in the cache.</p> <p>So my question is, is there constraints I can put on a generic that will allow me to return null regardless of the supplied type? (I'm assuming I need to use Nullable but not sure how.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload