How do I convert a string to a number so I can add another number to it in C#?

If I have a string with a value like "20", how can I convert it to an integer so I can add it to another number?

Here's some code that might explain how I want it to be:

string myString = "20";
myString = myString + 2;

Now the string myString should be "22".

Answers


You need to convert you string to int and then do addition. Later you can convert the resultant int to string.

For converting string to integer you can use Convert.ToInt32, int.Parse, or a safer option int.TryParse which would not raise an exception in case of invalid string.

int number1;
int number2 = 2;

if(!int.TryParse(myString, out number1)
{
  //invalid string
}
string result = (number1 + number2).ToString();

string myString = "20";
myString = Convert.ToString(Convert.ToInt32(myString) + 2);

You'l need to parse the string to do arithmetic:

string myString = "20";
myString = (int.Parse(myString) + 2).ToString();

This is how it can be done

string myString = "20";
int val = Convert.ToInt32(myString);
myString = (val + 2).ToString;

Not sure about your actual need, but for the sample code, you might be better with:

int myInt = 20;

myInt = myInt + 2;

//To do something:
something.Text = myInt.ToString();

Another fun way to do it is:

   using System.Data;

   //...

   string myString = "20";
   string addition = "+ 2";

   DataTable dt = new DataTable();

   myString = dt.Compute(myString + addition, string.Empty).ToString();

And here is even more fun:

using System;
using System.CodeDom.Compiler;

//...

string myString = "20";

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
ICodeCompiler icc = codeProvider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
CompilerResults results = icc.CompileAssemblyFromSource(
    parameters,
    string.Format(@"
namespace N{{
public static class C{{
public static string M(){{
return ({0} + {1}).ToString();
}}}}}}",
        myString,
        "2"));

myString = results
    .CompiledAssembly
    .GetType("N.C")
    .GetMethod("M")
    .Invoke(null, null)
    .ToString();

Of course none of this is recommended, unless there is no other way. Posted just as a curiosity :-)


string myString = "20";
int num = Convert.ToInt32(myString) + 2;
myString = num.toString();

Need Your Help

Waiting for an object to be instantiated in backbone

javascript backbone.js

I'm having a hard time figuring out how best to do this. I have a model that instantiates a few collections in its initialize method. Immediately after instantiating that model, I need to get a mod...