8

I'm trying make a program where you call operations like addition from classes.

I don't know why there's an error:

public string Add() {
    string AdditionTotal;
    int num1 = int.Parse(txtFirstNumber.Text);
    int num2 = int.Parse(txtSecondNumber.Text);
    AdditionTotal = num1 + num2; //throws an error here           
    return AdditionTotal;
}

public string SetText {
    get {
        return txtFirstNumber.Text;
    }
    set {
        txtFirstNumber.Text = value;
    }
}

4 Answers 4

14

Try like this

AdditionTotal = (num1 + num2).ToString(); 

num1 and num2 both is an int and their sum is also an int

C# can't convert it directly from int to string .

you have to cast it pragmatically in order to assign.

Sign up to request clarification or add additional context in comments.

Comments

0

AdditionTotal is of type of string and you are assigning int to it. Make AdditionTotal an int and return AdditionTotal.ToString()

Comments

0

The result of int + int is an int and you are trying to assign it to a string variable.

AdditionTotal should be an int and return type of method an int, or return AdditionTotal.ToString()

public int Add(int Total) {
    int AdditionTotal;
    int num1 = int.Parse(txtFirstNumber.Text);
    int num2 = int.Parse(txtSecondNumber.Text);
    AdditionTotal = num1 + num2; //throws an error here

    return AdditionTotal;
}

Comments

0

AB= (A + B).ToString(); Resulted AB will store the sum of A and B (int) and convert it to string. AB will have sum of a and b but in string format like a=2,b=3 then AB="5".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.