It tells me "use unassigned local variable "date" and won't even let me compile.
Shouldn't I enter the Try and at runtime maybe give me an error?
DateTime fecha;
try
{
Console.Write("Fecha de nacimiento: ");
nacimiento = Console.ReadLine();
fecha = Convert.ToDateTime(nacimiento);
}
catch (Exception)
{
Console.WriteLine("Error: El formato debe ser en dd/mm/aa");
}
Console.WriteLine(fecha);
Short answer: it's out of scope.
This works:
This also works:
The reason why this works is the "null" declaration of the "date", we achieve this thanks to the "?" character.
You can define it in the following way too:
I recommend you read about null types: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/
At the moment of doing
DateTime fecha;
it, you do nothing more than reserve a DateTime type object, however this does not mean making an objectDateTime
, for this you have to initialize it (DateTime fecha = new DateTime();
) or make it null (DateTime fecha = null;
). The error message happens because in case ittry
fails, at no time does it manage to initialize the variable.The error message:
it is because you have to initialize the variable
fecha
, you must initialize it:This would be the complete code: