views:

150

answers:

5

I'm familiar with:

Convert.ToInt32(texthere);

But is there another cleaner way to do it? I like having readable code for coworkers and I'm always on the lookout for anything that'll make my work seem more obvious.

+9  A: 

You can also use Parse and TryParse methods of int, double, float and decimal types.

Andrew Bezzub
+5  A: 

int.TryParse / double.TryParse

dtb
+2  A: 

Int.parse, float.parse and so forth.

Finglas
+8  A: 

What's not obvious about Convert.ToInt32 ?

Convert this value To an Int32 ?

Sam
+2  A: 

Personally I would use the standard methods stated (Convert.ToInt32, double.TryParse etc), but if you want an alternative ...

You could add an extension method, something like this (not tested it):

public static class Extensions
{
        public static int ConvertStringToInt(this string s)
        {
                return Convert.ToInt32(s);
        }
        public static long ConvertStringToLong(this string s)
        {
                return Convert.ToInt64(s);
        }
}

And then you could:

        string test = "1234";
        int testToInt = test.ConvertStringToInt();
        long testToLong = test.ConvertStringToLong();
amelvin
If you mark an answer down, could you give a reason, please?
amelvin
+1 for uniqueness. I'm not sure why someone downvoted, but this is a nice alternative solution. Personally I would use shorter methods like just `ToInt` but that's just a personal preference.
Sam
your method names are misleading. ConvertStringToInt should return Int32, ConvertStringToDouble should return Int64
Mel Gerats
@Sam, yes a shorter method name would probably be better - but I was looking for something more descriptive!
amelvin
@Mel Sorry about that, corrected.
amelvin
Not sure that two downvotes were necessary!
amelvin
@amelvin, the return types are still incorrect actually. `ConvertStringToInt` should return `int`, it currently shows `string`. `ConvertStringToLong` should return `long` but currently shows `string` as well. Then both are used in your example as returning `int` and then `double` which in this case would be a compiler error.
Sam
@Sam I hadn't tested the code before posting it and you are correct. I've just built it and fixed the compiler errors, tested the outcome and adjusted the code. Thanks for the heads up.
amelvin