Best way converting object into type of object like int, int32, decimal, double etc.

 on Wednesday, July 20, 2016  

if you ask me, how is the best and fast way converting object into numeric? was it using function Convert object like Convert.ToDecimal("object") ?
Or casting object as decimal ex. var result = (decimal)object; ?

The answer is NO! using that object has much possibility of error. if the object is null the object Convert has no good handling function.

The best way like the code below.

     [AllowAnonymous]  
     [HttpPost]  
     public JsonResult JsonLogin(LoginModel model, string returnUrl)  
     {  
       decimal result = 0;  
       if (decimal.TryParse(string.Format("{0}", model.Password), out result))  
       {  
         Console.Write("Your password is numeric : {0}", result);  
       }  
       else Console.Write("Your password is not numeric : {0}", result);  

Pay attention to the bold code  above, first machine will try to convert password into decimal, if the converting succeed then the value would be given into result, other wise the function TryParse return false. that means the converting executed failed!

The same thing with others. in dotnet, every type of object has TryParse function. have nice try!
Best way converting object into type of object like int, int32, decimal, double etc. 4.5 5 .NET-1235 Wednesday, July 20, 2016 if you ask me, how is the best and fast way converting object into numeric? was it using function Convert object like Convert.ToDecimal(...


No comments:

Post a Comment

Copyright © .Net-1235. All Rights Reserved.