Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, using ++ operator on value obtained via property (get)

Tags:

c#

properties

In C# we define a property as follows:

// m_age is a private int in the class Employee
public int Age
{
    get {return m_age;}
    set {m_age = value;}
}

Now, when I do

static void Main()
{
    Employee e = new Employee(age: 28); // Create new Employee
    System.Console.WriteLine("Age: {0}", e.Age); // Prints 28
    
    // Now increase age by 1
    ++e.Age;

    System.Console.WriteLine("Age: {0}", e.Age); // Prints 29
}

Why does the

++e.Age;

work? I did some searching and found Properties - by value or by reference?

This post had an answer:

Technically it's always by value, but you have to understand what is being passed. Since it's a reference type, you are passing a reference back (but by value).

Hope that makes sense. You always pass the result back by value, but if the type is a reference you are passing the reference back by value, which means you can change the object, but not which object it refers to.

(I do have a good understand of value-types and reference-types, hence my confusion).

Now, if indeed

e.Age

returns a copy of m_age (int is a value-type), won't we apply the increment ++ to the copy?

Or...is the following true?

++e.Age;

is exactly the same/gets translated to

e.Age = e.Age + 1

only that

++e.Age;

returns a value (the value of e.Age after it has been incremented) whereas

e.Age = e.Age + 1

is an assignment and does not return a value (like C++ would do for example).

like image 265
jensa Avatar asked Jan 08 '23 05:01

jensa


1 Answers

The ++ operator, unless redefined, will get, modify and set the value again.

A good way to check this is to define the get and set and go through in debug mode. This behavior is also detailed in the C# specification for increment and decrement operators.

like image 72
Philippe Paré Avatar answered Jan 09 '23 19:01

Philippe Paré