Why I am getting this error? cs(28,27):error CS0019 : operator '-' cannot be applied to operands of type 'string' or 'int' | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why I am getting this error? cs(28,27):error CS0019 : operator '-' cannot be applied to operands of type 'string' or 'int'

/* why I am getting this type of error.How to resolve this ? cs(28,27):error CS0019 : operator '-' cannot be applied to operands of type 'string' or 'int'*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class A { protected int a; protected int b; public virtual void eval(int i,int j) { a=i; b=j; Console.WriteLine("Sum:"+a+b); } } class B:A { public override void eval(int i,int j) { a=i; b=j; Console.WriteLine("Sub:"+a-b); } static void Main(string[] args) { A o1=new A(); o1.eval(4,3); B o2=new B(); o2.eval(4,3); } } } https://code.sololearn.com/clZDrrruH7SQ/?ref=app

23rd Jun 2021, 3:41 AM
Ur-Wellwisher
Ur-Wellwisher - avatar
3 Answers
0
You didn’t have the same error because it just joined it all as a string as o1(4,3) = 7 your code outputs 43 because: “Sum:” + “4” + “3” = sum:43 You need the brackets so it treats it as a mathematical operation and does it first then the addition It’s an order of operations things
23rd Jun 2021, 4:08 AM
Ollie Q
Ollie Q - avatar
0
Hi Ur Well-wisher Wrap the a-b in () like (a-b) Will fix the error which is that it is trying to concat (join) them all together and goes from left to right due to order of operations so wrapping them in brackets fixes the issue because it will be evaluated before the concating because you can subtract strings
23rd Jun 2021, 3:45 AM
Ollie Q
Ollie Q - avatar
0
But I didn't faced any problem with '+' operator. why?
23rd Jun 2021, 3:57 AM
Ur-Wellwisher
Ur-Wellwisher - avatar