I just started learning C#. I would like the Calculate method to be able to return objects of different types from Result class but I receive "Error CS0029 Cannot implicitly convert type 'string' to 'Calculator.Backend.Result'" and "Error CS0029 Cannot implicitly convert type 'int' to 'Calculator.Backend.Result'". I understand what they mean but I have no idea how am I supposed to solve these problems. Thank you for help in advance and sorry if my question is too basic.
public class Result
{
public string Message = "Test";
public int Value;
}
public class Calculator
{
public Result Calculate(string request)
{
Result Message = new Result();
if (request == null)
{
return Message.Message;
}
else
{
return Message.Value;
}
}
}
CodePudding user response:
My psychic debugging powers are telling me that you want to display int
when the result of the calculation is a number, and you want to display a string
with an error message when there is an error performing the calculation.
If that's the case, I'd probably just return the whole message as a Result
, and then where you're actually showing output, just use a string:
Console.WriteLine("Result: {0}",
string.IsNullOrEmpty(result.Message) ? result.Value.ToString() : result.Message);