Click here to Skip to main content
16,016,580 members
Please Sign up or sign in to vote.
1.40/5 (3 votes)
See more:
change string like 129 into integer type 129 without using typecasting as convert.toint32(string)....
thank you
Posted
Comments
Thanks7872 7-Aug-13 8:17am    
Why to avoid Convert.ToInt32()? Any specific reasons?
Zoltán Zörgő 7-Aug-13 8:27am    
Is this your homework? If so, struggle a little bit...

C#
int x = 0;

       Int32.TryParse("100", out x);
 
Share this answer
 
Comments
Manas Bhardwaj 7-Aug-13 8:28am    
Yup! 5ed!
Parse the string into chars, multiply each char int value by 10^(reversed index of char);

C#
using System;
using System.Linq;

namespace ParseTest
{
    public class Program
    {
        static void Main()
        {
            var s = "129";
            var r = s.Reverse();
            var sum = 0;
            for (var i = 0; i < r.Count(); ++i)
            {
                sum += (r.ElementAt(i) - '0') * (int)Math.Pow(10, i);
            }

            Console.WriteLine("int is {0}", sum);
        }

    }
}



Also, I don't think I need to point out that you shouldn't be doing this if this is for a real application, use the built in conversions instead.

But, for as a purely academic exercise, the above should work.

Hope this helps,
Fredrik
 
Share this answer
 
Comments
Manas Bhardwaj 7-Aug-13 8:28am    
Nice +5!
I am not sure if Google [^]is broken at your place? Or they blocked MSDN?

Look at the MSDN documentation to do this.

http://msdn.microsoft.com/en-us/library/vstudio/bb397679.aspx[^]

I would recommend to look into
C#
Int32.TryParse(string, out int)
as well.
 
Share this answer
 
Comments
Maciej Los 7-Aug-13 8:33am    
Very good link!
+5!
Manas Bhardwaj 7-Aug-13 8:34am    
thx!
It's not possible!

Please, read it: Casting and Type Conversions (C# Programming Guide)[^]
MSDN:
Because C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or used to store values of another type unless that type is convertible to the variable's type. For example, there is no conversion from an integer to any arbitrary string. Therefore, after you declare i as an integer, you cannot assign the string "Hello" to it, as is shown in the following code.
 
Share this answer
 
Comments
Manas Bhardwaj 7-Aug-13 8:27am    
Good one +5!
Maciej Los 7-Aug-13 8:31am    
Thank you, Manas ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900