C # extension method does not work for increase and decrease scenarios, is it by design?

I am trying to use a simple example of an extension method and cannot increase or decrease the value of int. Here is the code

static class ExtensionMethodsExp
{
    public static void Print(this object o)
    {
        Console.WriteLine("This is print: {0}", o.ToString());
    }

    public static int Double(this int i)
    {
        return i * 2;
    }
    public static int Decrement(this int i)
    {
         return i--;
    }

    public static int Increment(this int i)
    {
        return i++;

    }
}

}

Program code

class Program
{
    static void Main(string[] args)
    {

       int myNumber = 10;
       myNumber.Print();

       myNumber = myNumber.Double();
       myNumber.Print();

       myNumber = myNumber.Decrement(); 
       myNumber.Print();

       myNumber = myNumber.Increment();
       myNumber.Print();

       myNumber.Increment().Double().Print();
       Console.ReadKey();
    }
}

I get the following output

This print is: 10

This print is: 20

This print is: 20

This print is: 20

This print is: 40

Any idea why Decrement or Increment should not work here. Is there something I'm missing? thanks

+3
source share
5 answers

Try the following:

public static int Decrement(this int i)
{
     return --i;
}

public static int Increment(this int i)
{
    return ++i;
}
+8
source

The reason your code is not working is due to the way you use the Increment and Decrement statements.

When you write:

return i++;

The value I returns before the increment occurs.

Try the following:

return ++i;

or better yet:

return i + 1;
+5

, .

, i++ . , . , Increment().

++i, , , , .

, Increment Decrement, . ref this i? , ref , . .

+3

This is due to the fact that I ++ does not increase the number until the function is fully evaluated. Unfortunately, in your example, you are returning the original value, and incrementing the value is lost on the stack!

++ I increase I before the function evaluates.

0
source

++i means:

  • Increase i
  • Return value

i++ means:

  • Remember the current value of i
  • Increase i
  • Remember the previous i value (i.e. before you increased it)

One is called the "preincrement" statement, and the other is called the "postincrement" statement.

0
source

Source: https://habr.com/ru/post/1708996/


All Articles