Search code examples
c#coalesce

Null Coalescing for String to Int


I want to do a checking on a textbox, if null then assign zero, after that proceed with some calculation. I know there is a null coalescing (??) operator can help me, but I'm not sure is it possible for me to assign int when textbox is empty.

I tried to write something like this, but seems like is an error.

sdowntime = Convert.ToInt32(txtSDown.Text) ?? 0;

I get this

Error 98 Operator '??' cannot be applied to operands of type 'int' and 'int'

Anything I made it wrong or actually I should use another method? Please guide. Thank you very much!


Solution

  • You could also use the TryParse method, like so:

    int sdowntime;
    int.TryParse(txtSDown.Text, out sdowntime);
    

    If the TextBox is blank or contains a non-numeric value, the out parameter will be assigned the value 0. Otherwise, the appropriately parsed value is assigned. Please note, however, that you should always have client-side validation to ensure that non-numeric values are not entered by users in numeric fields.