S
sadhu
Hi All,
I was surprised to see the readonly behavior differ with respect to
properties and methods.
struct Foo
{
int state;
public int State
{
get { return state; }
set { state = value; }
}
public void SetState(int x)
{
state = x;
}
}
Now if I do something like
class Temp
{
readonly Foo f = new Foo();
public void SomeMethod()
{
f.State = 5; // Doesn't compile, ok
f.SetState(5); // Compiles !!!
}
}
The funny thing is although the method call succeeds, the state
variable in f doesn't change. Using ildasm, I can see that indeed, the
methodcall was made on a copy of f, like
Foo f2 = f;
f2.SetState(5);
One, I personally think that's misleading, it obviously looks like it
is calling the method on f. Two, why doesn't the same thing happen when
the State property was assigned to? After all, assignment to a property
ultimately translates into a set method call. Ideally, the compiler
should report error on both statements.
What do you think?
Regards
Senthil
I was surprised to see the readonly behavior differ with respect to
properties and methods.
struct Foo
{
int state;
public int State
{
get { return state; }
set { state = value; }
}
public void SetState(int x)
{
state = x;
}
}
Now if I do something like
class Temp
{
readonly Foo f = new Foo();
public void SomeMethod()
{
f.State = 5; // Doesn't compile, ok
f.SetState(5); // Compiles !!!
}
}
The funny thing is although the method call succeeds, the state
variable in f doesn't change. Using ildasm, I can see that indeed, the
methodcall was made on a copy of f, like
Foo f2 = f;
f2.SetState(5);
One, I personally think that's misleading, it obviously looks like it
is calling the method on f. Two, why doesn't the same thing happen when
the State property was assigned to? After all, assignment to a property
ultimately translates into a set method call. Ideally, the compiler
should report error on both statements.
What do you think?
Regards
Senthil