Search code examples
c#mvvmtryparse

Int32.TryParse C# - How to keep the last integer value


I'm trying to convert a string to int with

Int32.TryParse(input, out int number);

and I want to keep the last integer value. E.g. If string input = "123" then int number = 123 and if string input = "" or null then int number should stay 123 till input had a new string value.

Have someone a idea?


Solution

  • Keep a copy of the previous value, and if the parse failed copy it back in:

    var previousValue = 1;
    if(!int.TryParse(input, out var number))
    {
       number = previousValue;
    }