Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Method returning different value types from the same class

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;
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading