C # increment ToString

I am adding unexpected behavior from C # / WPF

    private void ButtonUp_Click(object sender, RoutedEventArgs e)
    {
        int quant;
        if( int.TryParse(Qnt.Text, out quant))
        {
            string s = ((quant++).ToString());
            Qnt.Text = s;
        }
    }

So, if I get the quantum as 1, the quantum will be increased to 2. But the string s will be 1. Is this a matter of priority?

EDIT:

I rewrote this as:

            quant++;
            Qnt.Text = quant.ToString();

and now it works as i expected.

+5
source share
5 answers

The post-increment operator is used. This is calculated to its original value and then increased. To do what you want in a single layer, you can use the pre-increment operator instead.

(++quant).ToString();

But it would be even better to avoid all such traps and do it like this:

quant++;
string s = quant.ToString();

, . . , .

, - , . , C 1970- , .

+6

, - ... ? () ToString:

if (int.TryParse(Qnt.Text, out quant))
{
    quant++;
    Qnt.Text = quant.ToString();
}

, , :

if (int.TryParse(Qnt.Text, out quant))
{
    Qnt.Text = (quant + 1).ToString();
}

. .

, , , , - int, . :

private void ButtonUp_Click(object sender, RoutedEventArgs e)
{
    // This is an int property
    Quantity++;
    // Now reflect the change in the UI. Ideally, do this through binding
    // instead.
    Qnt.Text = Quantity.ToString();
}
+6

, ... , ++ ++ i? , : -)

... pre-increment post-increment? , ( , ):

(, i + 1), (, i + 1), ( i + 1). , i. : " ?" :

  • pre increment ++i: i i
  • post increment i++: i i

... , increments i . ( ).

( Lippert . , , , , , , ) ( )

1:

unchecked
{
    int i = Int32.MaxValue;
    Console.WriteLine("Hello! I'm trying to do my work here {0}", i++);
    Console.WriteLine("Work done {1}", i);
}

2:

checked
{
    int i = Int32.MaxValue;
    Console.WriteLine("Hello! I'm trying to do my work here {0}", i++);
    Console.WriteLine("Work done {1}", i);
}

checked , (OverflowException). unchecked , . Int32.MaxValue + 1 . checked , unchecked i -1.

. :

Hello! I'm trying to do my work here 2147483647
Work done -1

... i , Console.WriteLine (Int32.MaxValue == 2147483647). - Console.WriteLine.

. :

System.OverflowException: Arithmetic operation resulted in an overflow.

... , -, , , , Console.WriteLine ( ).

, , , , .

. ? , . Pre post increments C # . ( , ++ !). , , -, , .

"" -

for (int i = 0; i < x; i++)

i++; // Written alone. Nothing else on the same line but a comment if necessary.

""

(nothing)
+1

quant.ToString(), .

((++quant).ToString()), , quant.ToString().

-1

string s = ((quant++).ToString());

can be distributed as

use quantto call the toString () method before the increment, and then

execute an assignment statement and then

increment `quant '

try c ++ quantum.

-1
source

All Articles