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...
Double TryParse(String, Double) converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.
Convert a string representation of number to an integer, using the int. TryParse method in C#. If the string cannot be converted, then the int. TryParse method returns false i.e. a Boolean value.
TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
I'm usually using this extension method in LINQ queries:
public static DateTime? TryGetDate(this string dateString, string format = null)
{
DateTime dt;
bool success = format == null ? DateTime.TryParse(dateString, out dt) : DateTime.TryParseExact(dateString, format, null, DateTimeStyles.None, out dt);
return success ? dt : (DateTime?)null;
}
You use it in this way:
user.DataNascita = txtDataDiNascita.Text.TryGetDate();
Here's another overload with multiple formats and an IFormatProvider
(different cultures):
public static DateTime? TryGetDate(this string dateString, IFormatProvider provider, params string[] formats)
{
DateTime dt;
var success = DateTime.TryParseExact(dateString, formats, provider, DateTimeStyles.None, out dt);
return success ? dt : (DateTime?)null;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With