Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>Convert.ToInt32</code> just returns <code>int</code>, not <code>int?</code> - so the type of the expression:</p> <pre><code>size ?? Convert.ToInt32(...) </code></pre> <p>is of type <code>int</code>. You can't use a non-nullable value type as the first operand of a null-coalescing operator expression - it can't possibly be null, so the second operand (10 in this case) could never possibly be used.</p> <p>If you're trying to <em>try</em> to use the <code>StoriesPageSize</code> cookie, but you don't know whether or not it's present, you could use:</p> <pre><code>public ActionResult Index(string keyword, int? page, int? size) { keyword = keyword ?? ""; page = page ?? 1; size = size ?? GetSizeFromCookie() ?? 10; } private int? GetSizeFromCookie() { string cookieValue = Request.Cookies.Get("StoriesPageSize").Value; if (cookieValue == null) { return null; } int size; if (int.TryParse(cookieValue, CultureInfo.InvariantCulture, out size)) { return size; } // Couldn't parse... return null; } </code></pre> <p>As mentioned in comments, you could write an extension method to make this more generally available:</p> <pre><code>public static int? GetInt32OrNull(this CookieCollection cookies, string name) { if (cookies == null) { throw ArgumentNullException("cookies"); } if (name == null) { throw ArgumentNullException("name"); } string cookieValue = cookies.Get(name).Value; if (cookieValue == null) { return null; } int size; if (int.TryParse(cookieValue, CultureInfo.InvariantCulture, out size)) { return size; } // Couldn't parse... return null; } </code></pre> <p>Note that I've changed the code to use the invariant culture - it makes sense to propagate information in cookies in the invariant culture, as it's not really meant to be user-visible or culture-sensitive. You should make sure you <em>save</em> the cookie using the invariant culture too.</p> <p>Anyway, with the extension method in place (in a static non-generic top-level class), you can use:</p> <pre><code>size = size ?? Request.Cookies.GetInt32OrNull("StoriesPageSize") ?? 10; </code></pre>
 

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