These are the list of
extension methods used to Convert String/Object to Other Data type.
Just Copy, Paste and reuse
it.
Method Name
Description
ParseInt
Converts Object/String to Integer
ParseDec
Converts Object/String to Decimal
ParseDate
Converts Object/String to DateTime
ParseLong
Converts Object/String to Long
ParseBool
Converts Object/String to Bool
Source Code: Just
Copy and Paste
Code
namespace ExtensionMethods
{
using System;
///<summary> ///
Used to convert one data type to another. ///</summary> publicstaticclassDataConversion {
#region
Int methods
///<summary> ///Converts
object to Integer if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticint
ParseInt(this
object value, int ifNone)
{ if (value ==
null)
{ return ifNone;
} return ParseInt(""
+ value, ifNone);
}
///<summary> ///Converts
string to Integer if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticint
ParseInt(this
string value, int ifNone)
{ int i = ifNone; if (!int.TryParse(value,
out i))
{
i = ifNone;
} return i;
}
#endregion
#region
Dec methods
///<summary> ///Converts
object to decimal if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticdecimal
ParseDec(this
object value, decimal ifNone)
{ if (value ==
null)
{ return ifNone;
} return ParseDec(""
+ value, ifNone);
}
///<summary> ///Converts
string to decimal if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticdecimal
ParseDec(this
string value, decimal ifNone)
{ decimal d = ifNone; if (!decimal.TryParse(value,
out d))
{
d = ifNone;
} return d;
}
#endregion
#region
Date methods
///<summary> ///Converts
string to datetime if the value is valid, otherwise returns ifnone
value. ///</summary> publicstatic
DateTime ParseDate(thisstring date,
DateTime ifNone)
{ DateTime res = ifNone; if (!DateTime.TryParse(date,
out res))
{
res = ifNone;
} return res;
}
#endregion
#region
Long methods
///<summary> ///Converts
object to long if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticlong
ParseLong(this
object value, long ifNone)
{ if (value ==
null)
{ return ifNone;
} return ParseLong(""
+ value, ifNone);
}
///<summary> ///Converts
string to long if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticlong
ParseLong(this
string value, long ifNone)
{ long i = ifNone; if (!long.TryParse(value,
out i))
{
i = ifNone;
} return i;
}
#endregion
#region
Bool Methods ///<summary> ///Converts
string to bool if the value is valid, otherwise returns ifnone value. ///</summary> publicstaticbool
ParseBool(this
string value, bool ifNone =
false)
{ bool res = ifNone;
value = "" + value; if (value.Length > 1)
{
value = value.Substring(0, 1);
}
value = value.ToLower(); if (value ==
"1" || value ==
"t" || value ==
"y")
{
res = true;
} elseif (value ==
"0" || value == "f" || value
== "n")
{
res = false;
} return res;
}
Join the conversation! Your thoughts help the community grow.