-1

Ok so i have this control: https://github.com/TBertuzzi/Xamarin.Forms.MaskedEntry

<control:MaskedEntry Placeholder="HH:MM:SS" Mask="XX:XX:XX" Keyboard="Numeric" Text="{Binding TaskDuration}" TextChanged="DurationIs8"></control:MaskedEntry>

In my app, the user enters a duration with this format hours:minute:second

Then this method is executed when saving the item, to get the duration to later use it for calculation :

public static TimeSpan GetDuration(string duration)
{
    if(duration != null)
    {
        var value = duration.Split(':').Select(int.Parse).ToArray();
        var datetime = new TimeSpan(value[0], value[1], value[2]);
        return datetime;
    }
    return TimeSpan.Zero;
}

My Problem is that i want to be able to deal with cases where the user only enters, example : 02:0 Everytime i click the save button, i get the duration which generates the error if the MaskedEntry doesn't respect the format.

Currently this generate an index out of range exception everytime the GetDuration method is called because this line: var datetime = new TimeSpan(value[0], value[1], value[2]); tries to access array value that doesn't exist.

Anyway to handle this so my app doesn't crash if the user doesn't complete the maskedentry ? Thanks a lot.

codetime
  • 209
  • 2
  • 9
  • Yes. There are many ways you can handle this. To start with, don't assume there are always 3 values in the array returned by `Split`. And add a try/catch block to handle any exceptions. – Jason Sep 09 '20 at 19:57

1 Answers1

-1

to start with, don't assume there are always 3 values in the array returned by Split. And add a try/catch block to handle any exceptions.

public static TimeSpan GetDuration(string duration)
{
    try {
      if(!String.IsNullOrEmpty(duration)
      {
          var values = duration.Split(':');

          int h,m,s;

          if (values.Length > 0) {
            h = int.Parse(values[0]);
          }

          if (values.Length > 1) {
            m = int.Parse(values[1]);
          }

          if (values.Length > 2) {
            s = int.Parse(values[2]);
          }

          var datetime = new TimeSpan(h,m,s);
          return datetime;
      }
   } catch (Exception ex) {
     // log exception or display error message
   }

   return TimeSpan.Zero;
}
Jason
  • 86,222
  • 15
  • 131
  • 146
  • There is no logic here that should throw an exception. If the number of tokens returned is an issue, that is _much_ better handled by checking the length of the returned array before trying to index it. If the validity of the tokens as numeric values is an issue, then calling `TryParse()` is a _much_ better option. And frankly, the `TimeSpan.TryParseExact()` method would be a way better approach than any of this. – Peter Duniho Sep 09 '20 at 20:50