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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -