-- or ++ operators on ReadOnly property

  • Thread starter Thread starter Sacha Faust
  • Start date Start date
S

Sacha Faust

if you have a ready only properly like string.Length and I do
--(string.Length) I get a compiler problem saying that I can't modify the
value of the readonly property.

From my understanding, the -- operator should be decrementing the value
return by (string.Lenght) and not string.Lenght directly.

Am I right or just completely wrong on this and should get more sleep.
If I'm wrong can you give details.

Tks.
 
Sacha Faust said:
if you have a ready only properly like string.Length and I do
--(string.Length) I get a compiler problem saying that I can't modify the
value of the readonly property.

From my understanding, the -- operator should be decrementing the value
return by (string.Lenght) and not string.Lenght directly.

No.

Essentially, --PropertyName is:

(PropertyName=PropertyName-1) with the result being the already
decremented version.

What did you want --(string.Length) to actually achieve? Could you give
an example of where you'd use it?

See section 14.6.5 of the ECMA C# spec for more details.
 
Hi Sacha,
-- and ++ requires *l-value* in other words it needs storage location,
property or indexer because it changes the value kept on it
Those operators cannot be applied on constants.
If you want to decrement the value returned by that property simply do

int a = obj.Prop - 1;

HTH
B\rgds
100
 
You want to use 'stringVar.Length - 1' and get more sleep ;)

x = --variable; // Same as variable = variable - 1; x = variable;
x = variable--; // Same as x = variable; varaible = variable - 1;
x = ++variable; // Same as variable = variable + 1; x = variable;
x = variable++; // Same as x = variable; variable = variable + 1;

Tom Clement
Apptero, Inc.
 
logically
--variable and --(variable) should be different.

I think that the LValue explains some of the issue.
 
Sacha Faust said:
logically
--variable and --(variable) should be different.

I don't see why. What would you expect --(variable) to do differently?
Again, could you give an example of how you'd expect to use it?
 
Good point. I wasn't paying close enough attention to your original post.
It is true that (variable) is not an lvalue, as Jon pointed out, and so
cannot be modified.
Sorry for my misunderstanding.

Tom Clement
Apptero, Inc.
 
Sacha said:
logically
--variable and --(variable) should be different.

I think that the LValue explains some of the issue.

Parentheses do not change whether an expression is an l-value or not.
This is the case in C, C++, and C#. It may be different in other languages.

If you look carefully at the language specs for each of these languages,
an expression surrounded by parentheses does not create a new object -
the type and value are identical to what is inside the parentheses.
 
Back
Top