Hi Zorro26,
basically the + operator has been overridden in the AddClass1 type to
allow addition of two classes to produce a third result. So the + operator
knows how to handle the semantics of adding two AddClass1's together to
produce a third AddClass1 with the sumation result.
For example:
class AddClass1
{
private int m_intValue;
public AddClass1()
{
}
public int Value
{
get
{
return m_intValue;
}
set
{
m_intValue = value;
}
}
//Overload the + operator, so you can see how the binary + operator
//takes ac1,ac2 parameters and adds them together internally and returns
//a new instance with the result of the summation
public static AddClass1 operator + (AddClass1 ac1, AddClass1 ac2)
{
AddClass1 acResult;
acResult = new AddClass1();
acResult.Value = ac1.Value + ac2.Value;
return acResult;
}
}
That is why you can now say:
AddClass1 acResult = a1 + a2; //where a1,a2 are previously defined
instances of AddClass1 like in your example.
Hope that helps
Mark R Dawson
"Zorro26" wrote:
I have a question about the following code in C#:
AddClass1 op1=new AddClass1();
op1.val=5;
AddClass1 op2=new AddClass1();
op2.val=3;
AddClass1 op3=op1+op2;
Console.WriteLine(op3.val);
The answer is of course 8. but my question is:
Why don't i need to initialize op3 in the form of AddClass1 op3=new
AddClass1();
like with op1 and op2 ?