my code snippet has something different in that it will never cause an "unassigned" error
Well it clearly does cause that error, which is why you asked the question, no?
Even though you know that any time the exception is thrown, you'll go round the loop again, the compiler doesn't know that... hence the error. The value is not definitely assigned. Of course, you could just give it a dummy value to start with - but personally I don't like doing that.
You'd be better off extracting the parsing code into a separate method, which could look something like:
static DateTime RequestStartDate()
{
while (true)
{
try
{
// Ask for date and parse it
// ...
return parsedDate;
}
catch (Exception e) // See below...
{
MessageBox.Show("The date entered is not valid");
}
}
}
That method will definitely return a DateTime
eventually, or keep looping forever - so any variable assigned by calling that method will be definitely assigned.
Then in your main code you can write:
switch (userType)
{
case "Doctor":
string qualification = Microsoft.VisualBasic.Interaction.InputBox("What is the highest qualification this person has", "Qualification", "", -1, -1);
DateTime dateStarted = RequestStartDate();
string field = Microsoft.VisualBasic.Interaction.InputBox("In which field does this person practice", "Field", "", -1, -1);
CreateDoctor(qualification, dateStarted, field);
break;
As an aside, you're calling string.Remove
and ignoring the result - always a bad idea. And parsing the date manually is needlessly complicated - use DateTime.TryParseExact
.
Additionally, catching Exception
is usually a bad idea - you should catch specific exceptions... although if you use DateTime.TryParseExact
you won't need to catch anything, as it will just return false
if the value can't be parsed.
I'd also advise you to at least have a using
directive for Microsoft.VisualBasic
so that you can just use:
string qualification = Interaction.InputBox(...);
etc instead of having a hugely long line each time.