Hi
Given the following code I came across:-
class MyImmutableType
{
public readonly double x;
public MyImmutableType(double _x) { x = _x; }
public MyImmutableType Square() { return new MyImmutableType(x*x); }
}
static double SomeMethod(MyImmutableType t)
{
t = t.Square();
return t.x;
}
Why does the return statement have to be t.x;
rather than just t, as t holds the return value of Square?
I appreciate that the return type of SomeMethod is double and x is of type double so it could be due to a type conversion\cast error.
Regards
Steven
Loading
VulpesPosted Aug 22, 2012, 5:12 AM
The return type of SomeMethod is double and the type of t.x is double, whereas the type of t is MyImmutableType. So the former matches but the latter does not.
Akkiraju IvaturiPosted Aug 21, 2012, 4:51 PM
Let us call it myId.
Now when you create an instance of MyImmutableType in the Main() method,
assign value to the property myID =178.
Debug the code by pressing F10 button. Before moving to the code t=t.square() check what is the value myID of "t". It shows 178. Now after executing t=t.square(), you check the value of myID and it shows 0.
This is because the square method of t is returning a new type and when you say executing square method, you are actually finding the square of x in the type t and not t. x is the double type which should be returned by your someMethod not myImmutableType. But why you are assigning t.square() to another myImmutable type is the square method return type is not a double, but the myImmutable type. What the square method returns is it squares the x in type t and returns type t.
So, you cannot return t as the value, but it should t.x.
Guest UserPosted Aug 21, 2012, 12:19 PM