Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better ways for type casting in C#

Tags:

c#

resharper

Case 1: we can convert type by the following ways .....

  1. First way

        int someInt = 10;
        double someDouble = (double) someInt;
    
  2. Same thing in second way

        int someInt = 10;
        double someDouble = Convert.ToDouble(someInt);
    

Case 2: We can convert somethings into string by the following ways .......

  1. First way

        int someInt = 10;
        string someString =  someInt.ToString();
    
  2. Second way

        int someInt = 10;
        string someString =  someInt.ToString(CultureInfo.InvariantCulture);
    

Now my question is which one is good?? I am asking this question because ReSharper always gives me suggestion like 2nd way for both cases. I don't which one should I follow.

like image 349
Atish Dipongkor Avatar asked Dec 22 '25 02:12

Atish Dipongkor


1 Answers

  1. Case 1 - both ways are equal, 1st way being little bit faster.
  2. Case 2 - 1st way could be dangerous, since int.ToString() uses Culture.CurrentCulture as an argument (and so results can vary from computer to computer):

as in:

someInt.ToString() == someInt.ToString(CultureInfo.CurrentCulture);
like image 118
Dmitry Bychenko Avatar answered Dec 24 '25 11:12

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!