c# - Parsing date and time, try-catch, variable for hours out of scope -
i want parse date , time. want catch if there format exception , following:
try { datetime time = datetime.parse(console.readline()); } catch (formatexception) { console.writeline("wrong date , time format!"); } however when start working value 'time' c# says "the name 'time' not exist in current context". mistake?
you've declared time within try block, it's out of scope after that. declare beforehand:
datetime time; try { time = ...; } catch (formatexception) { console.writeline("wrong date , time format!"); return; // or other way of getting out of method, // otherwise time won't assigned afterwards } however, better use datetime.tryparse instead of catching formatexception:
datetime time; if (datetime.tryparse(console.readline(), out time) { // use time } else { console.writeline("wrong date , time format!"); }
Comments
Post a Comment