Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Generic tryparse method 2

Status
Not open for further replies.

Badgers

Programmer
Nov 20, 2001
187
US
Hi,

I'm trying to do a generic tryparse for any data type, well stuff like int, double, decimal etc.

So if a value is null will just return defaulv value of 0.

here is an example of what i'd like to convert from:

protected decimal DecimalTryParse(object value)
{
decimal valueConverted = 0;

if (value != null)
{
decimal.TryParse(value.ToString(), out valueConverted);
}

return valueConverted;
}

Thanks inadvance

 
Code:
public T TryParse<T>(object value)
{
   if(value == null) return default(T);
   return (T) Convert.ChangeType(typeof(T), value);
}

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top