I’m trying create pagination on my page. The user can select the number of items that will appear per page, the preferred size then will be saved as cookie. But when I try to choose between the querystring parameter and cookie, an error occured:
public ActionResult Index(string keyword, int? page, int? size)
{
keyword = keyword ?? "";
page = page ?? 1;
//Operator "??" cannot be applied to operands of type "int" and "int"
size = size ?? Convert.ToInt32(Request.Cookies.Get("StoriesPageSize").Value) ?? 10;
What’s causing this error? How to fix it?
Convert.ToInt32just returnsint, notint?– so the type of the expression:is of type
int. 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.If you’re trying to try to use the
StoriesPageSizecookie, but you don’t know whether or not it’s present, you could use:As mentioned in comments, you could write an extension method to make this more generally available:
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 save the cookie using the invariant culture too.
Anyway, with the extension method in place (in a static non-generic top-level class), you can use: