Reputation: 137
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;
}
}
Upvotes: 8
Views: 39823
Reputation: 1
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".
Upvotes: 0
Reputation: 25352
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.
Upvotes: 14
Reputation: 10744
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;
}
Upvotes: 0
Reputation: 320
AdditionTotal
is of type of string
and you are assigning int
to it. Make AdditionTotal
an int
and return AdditionTotal.ToString()
Upvotes: 0