C # - are properties recounted every time they are accessed?

Assuming the following simple code:

private const int A = 2;
private const int B = 3;


public int Result
    {
        get
        {
            return A * B;
        }
    }

I use the Result property many times.
Is product A * B recounted every time?

+5
source share
8 answers

Opening the assembly in the reflector, the compiler optimizes the multiplication, since they const int:

public class FooContainer
{
    private const int A = 2;
    private const int B = 3;


    public int Result
    {
        get
        {
            return A * B;
        }
    }
}

It will become:

public class FooContainer
{
    // Fields
    private const int A = 2;
    private const int B = 3;

    // Properties
    public int Result
    {
        get
        {
            return 6;
        }
    }
}

But if you change the variables to simple intand don’t store the calculations, the evaluation will happen every time.

Example:

public class FooContainer
{
    private int A = 2;
    private const int B = 3;


    public int Result
    {
        get
        {
            return A * B;
        }
    }
}

becomes:

public class FooContainer
{
    // Fields
    private int A = 2;
    private const int B = 3;

    // Properties
    public int Result
    {
        get
        {
            return (this.A * 3);
        }
    }
}
+1
source

If you do not store this value in a private field, then yes, it will be recalculated at each access.

A way to cache results will consist of

private int? _result;
public int Result {
  get {
     if (!_result.HasValue) {
       _result = A*B;
     }
     return _result.Value;
  }
}

.

-, , . , . , .

-, , , "". , - .

-, getter (.. A B ), NOT .

, : , , , . , , - , .

+5

. , get_Xxx set_Xxx. , , get.

+3

const, .

const, .

+2

. , ​​, .

+1

, - , , . , -, , int, , , ( ):

int? _result = null;
public int Result {
    get {
        if ( _result == null )
            _result = A * B;
        return _result;
    }
}
+1

, . "-" " ", #, , " , ". -, .

, . (# , ), , . , A B CONSTS, , , , getter const.

. . , Microsoft ", ".

+1

, . - , .

0
source

All Articles