0

I don't understand why I am getting a cannot convert to string with _one but not the other 3! Yes, I'm new to programming and loosing my mind trying to figure out why stackoverflow is requiring me to enter more words than I needed to ask my question!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace diviTwo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Print Test Problems
            var n = "\n";
            var one = "-1 + 4 * 6";
            var two = "(35 + 5) % 7";
            var three = "14 + -4 * 6 / 11";
            var four = "2 + 15 / 16 * 1 - 7 % 2";
            Console.WriteLine(one+ n+ two+ n+ three+ n+ four+ n);

            //Print Results of Test Problems
            var _one = -1 + 4 * 6;
            var _two = (35 + 5) % 7;
            var _three = 14 + -4 * 6 / 11;
            var _four = (2 + 15) / ((16 * 1) - (7 % 2));
            Console.WriteLine(Convert.ToString(_one)+ n+ _two+ n+ _three+ n+ _four+ n);
        }
    }
}
  • Take another look at your own code: `Convert.ToString(_one)`. You are only converting `_one` to a string here, then trying to add the numeric variables to it. – Martin Nov 19 '18 at 13:14
  • 1
    Possible duplicate of [String Concatenation using '+' operator](https://stackoverflow.com/questions/10341188/string-concatenation-using-operator) – mjwills Nov 19 '18 at 13:16
  • What's the difference if you do not add? What is your problem? – SᴇM Nov 19 '18 at 13:20
  • Problem is I didn't understand how C# decides what to do in my last WriteLine. @RobinBennett explained that if that first item is a string C# treats the rest of them as strings. I didn't know that and spent sometime trying to figure out why/how to make it work without conversion, gave up and found out how to convert that _one which visual studio seemed to raise the error on. – HELLHOUND0606 Nov 19 '18 at 13:46

1 Answers1

1

There's nothing special about _one, it's just that if the first item is a string, C# knows that you want to treat everything else as a string and concatenate them. You'd get the same result if you did

Console.WriteLine("Result=" + _one + n + _two + n + _three + n + _four + n);

If you just supplied a list of variables that were all integers, C# would add them up and give you the result. However you start with a number and add a string, so C# doesn't know what to do.

Robin Bennett
  • 3,192
  • 1
  • 8
  • 18