I have a UnitTest and should test this method. I am getting the sum of strings. What I did is that I converted the string into integers and added them and store in the variable length as an Integer, and then I return the length. The problem that I have is that it is showing that it cannot resolve symbol length. I am using Rider as IDE and I changed the settings of the IDE, but it is still showing "Cannot resolve symbol length". I hope someone can help me to fix this.
internal string SumStrings(string value1, string value2)
{
int.Parse(length) = int.Parse(value1) + int.Parse(value2);
return length;
}
The UnitTest:
#region Sum of strings as string
// Create a method that returns the sum of two numbers.
[Fact]
public void ReturnsSumAsStringFromTwoString()
{
Assert.Equal("11", util.SumStrings("6","5"));
}
// Previous method must pass the following Multiple tests.
[Theory]
[InlineData("1", "1", "0")]
[InlineData("1", "0", "1")]
[InlineData("-1", "0", "-1")]
[InlineData("1000", "500", "500")]
public void TheoriesReturnsSumAsStringFromTwoString(string length, string value1, string value2)
{
Assert.Equal(length, util.SumStrings(value1, value2));
}
This is not how you declare and assign a variable:
int.Parse(length) = int.Parse(value1) + int.Parse(value2);
This is:
var length = int.Parse(value1) + int.Parse(value2);
Or if you want to specify the type explicitly:
int length = int.Parse(value1) + int.Parse(value2);
Additionally, your method claims to have a return type of string
but you are trying to return an int
. Change the return type:
internal int SumStrings(string value1, string value2) {
As an aside, in your method you don't really need a separate variable at all, you can just return the calculated result directly:
internal int SumStrings(string value1, string value2) {
return int.Parse(value1) + int.Parse(value2);
}
you are trying to do int.Parse(length)
while the length is not defined yet, and you are not returning a string but an Int.
internal string SumStrings(string value1, string value2)
{
var length = int.Parse(value1) + int.Parse(value2);
return length.ToString();
}
would work, but be careful, what would happen if the input is not a number? better use TryParse
int number;
bool success = int.TryParse(value, out number);
a better solution would be something like this:
internal string SumStrings(string value1, string value2)
{
if (int.TryParse(value1, out var num1) && int.TryParse(value2, out var num2))
{
return (num1+num2).ToString();
}
// throw new WrongInputException("wrong input");
// or some other default behavior as your requirements ask for
// basically some kind of handling for bad input value
}
as the comments section implies, you should of course catch the specific exception, and even create a new exception that suits your needs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.