I'm using the following methods to provide quick, inline access to the TryParse() method of various Type classes. Basically I want to be able to parse a string coming from a web service if possible or return a default value if not.
private Int64 Int64Parse(string value) {
Int64 result;
if (!Int64.TryParse(value, out result)) { return default(Int64); }
return result;
}
private DateTime DateTimeParse(string value) {
DateTime result;
if (!DateTime.TryParse(value, out result)) { return default(DateTime); }
return result;
}
private Decimal DecimalParse(string value) {
Decimal result;
if (!Decimal.TryParse(value, out result)) { return default(Decimal); }
return result;
}
These are extremely repetitive, suggesting, to me, that there may be a way to wrap them into a single generic method.
I'm stuck at the following but not sure how to proceed or how to search for how to proceed.
private T ParseString<T>(string value) {
T result;
if (!T.TryParse(value, out result)) { return default(T); }
return result;
}
Any help would be appreciated. Thanks.
==Edit== To add some context. This is for a listener receiving postbacks from a specific credit card billing company. I'm not doing validation at this step because that's being done in the business rules steps later. For example, I don't care if bank_batch_number comes in as an int, string or freeze-dried rodent; I'm not going to halt with an exception if I can't cleanly log a field I don't use. I do care that ext_product_id exists in our DB and has a price matching currency_amount_settled in the message; if that test fails then the transaction is put on hold, a warning is logged, and our CS staff and myself will be alerted.
The culture thing mentioned below is sage advice though.