Parse, Convert.To Pros & Cons :


Parse
Convert To
Try Parse
1) Doesn’t Handles null values. If input is null,It will throwArgumentNullException. 1) Handles null,doesn’t throw exception.
Instead it returns default value
1)Handles null,doesn’t throw exception.Instead it outs default value.
2) If input other than expected type, it will throwFormatException. 2)If input other than expected type, it will throw FormatException . 2) If input other than expected Type,It outs default value instead of format exception
3) If memory range voilates, it will throw OverflowException 3)If memory range voilates, it will throw OverflowException 3) If Memory range voilates, it outs default instead of OverFlowException
So TryParse is better to use.
But if you want to make sure of few customised validations uniformly across the code like
Ex : The default of string is null, the default of DateTime is 1/1/1. so in order to even default values to be on safer side, can have the Extension method to override the default values
string – string.Empty
DateTime – Current DateTime
namespaceExampleForConvertTo
{
publicpartialclassForm1: Form
{
publicForm1()
{
InitializeComponent();
}
protectedoverridevoidOnLoad(EventArgse)
{
base.OnLoad(e);
strings = default(string);//Null
inta = 0;
stringd = null;
a = d.ConvertTo<int>();//0
d = “S”;
a = d.ConvertTo<int>();//0
d = “9”;
a = d.ConvertTo<int>();//9
}
}
publicstaticclassMethodExtensions
{
publicstaticT ConvertTo<T>(thisobjectval)
{
try
{
objecttVal = Convert.ChangeType(val, typeof(T));
if(tVal == null) thrownewException();
else
{
return(T)tVal;
}
}
catch
{
return(T)((typeof(T) == typeof(string)) ? (object)string.Empty :
((typeof(T) == typeof(DateTime)) ? (object)(DateTime.Now) : (object)default(T))
);
}
}
}

}

Advertisements