Just a challenge I guess, but I hope to use TryParse in just one line :) My code:
DateTime tempDate;
user.DataNascita = DateTime.TryParse(txtDataDiNascita.Text, out tempDate) ? tempDate : (DateTime?)null;
user.DataNascita
is DateTime?
, and I want to return the data if TryParse is correct, null otherwise. But I need the out one (so, new line). Can't I have all in one line?
Just curious...
You'd need a helper method, basically. For example:
public static DateTime? TryParseDateTime(string text)
{
DateTime validDate;
return DateTime.TryParse(text, out validDate) ? validDate : (DateTime?) null;
}
Then you can just use:
user.DataNascita = ParseHelpers.TryParseDateTime(txtDataDiNascita.Text);
You'd probably want overloads corresponding with the overloads of DateTime.TryParse
and DateTime.TryParseExact
, too. I wouldn't personally make this an extension method as per Tim's answer, but that's a matter of personal preference.
See more on this question at Stackoverflow