Tuesday, 6 March 2012

How to Use Parse and TryParse Methods?

Yes,All Premetive types have the Parse,Try parse methods with maximum overloads.
Parse: Parse method is used to convert when our data in string to their approate type.
Ex:
           string value = "100";
           Console.WriteLine(value.GetType());

           int i = int.Parse(value);
           Console.WriteLine(i.GetType());

           string dt = DateTime.Now.ToString();          
           Console.WriteLine(DateTime.Parse(dt).GetType());
TryParse : TryParse method is used to convert when our data in string their apporiate type returns the a bool value. 
as well as  TryParse tell the value is  possibility to Converitable or not.

Ex:
           string v = "45";
           int k = 0;
           bool j = int.TryParse(v, out k);
           Console.WriteLine(k);
           Console.WriteLine(k.GetType());

Note: try to use this method if the convertable value in string.rather then using Convert() method.

No comments:

Post a Comment