visual studio 2010 - Result is getting 0 when using Operator Overloading in C# -
hi have below program , new c#,
using system; using system.collections.generic; using system.linq; using system.text; namespace unaryoperatoroverload { public class unaryoperator { private int number1; private int number2; private int result; public unaryoperator() { } public unaryoperator(int number1, int number2) { number1 = number1; number2 = number2; } public static unaryoperator operator +(unaryoperator opr) { unaryoperator obj = new unaryoperator(); obj.result = obj.number1 + obj.number2; return obj; } public void showdata() { console.writeline("the sum of 2 numbers : " + result); } } public class program { static void main(string[] args) { unaryoperator opr = new unaryoperator(20, 30); opr.showdata(); console.readline(); } } }
when execute code , getting result 0. not sure went wrong.please me rectify code.
your mistakes:
- you creating new
unaryoperator obj = new unaryoperator();
in operator overloading function.obj.number1
,obj.number2
's value0
, because have createdobj
instance. - you never calling + operator. add
opr = +opr;
statement inmain
method.
change code as:
public class unaryoperator { private int number1; private int number2; private int result; public unaryoperator() { } public unaryoperator(int number1, int number2) { number1 = number1; number2 = number2; } public static unaryoperator operator +(unaryoperator opr) { opr.result = opr.number1 + opr.number2; // change line return opr; } public void showdata() { console.writeline("the sum of 2 numbers : " + result); } } public class program { static void main(string[] args) { unaryoperator opr = new unaryoperator(20, 30); opr = +opr; // add statement opr.showdata(); console.readline(); } }
Comments
Post a Comment