Get-only property with constant value, auto-property or not?

Is there a performance / memory difference between the next two property declarations, and should I be preferable?

public bool Foo => true;

public bool Foo { get; } = true;

Also, does the situation change if Boolean is replaced with another immutable value (e.g. string)?

+4
source share
2 answers

I wrote this class as an example.

class Program
{
    public bool A => true;
    public bool B { get; } = true;
}

with reflection I decompiled the assembly and got this code

class Program
{
    // Fields
    [CompilerGenerated, DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly bool <B>k__BackingField = true;

    public bool A
    {
        get
        {
            return true;
        }
    }

    public bool B
    {
        [CompilerGenerated]
        get
        {
            return this.<B>k__BackingField;
        }
    }
}

@Fruchtzwerg , , getter, ture, , true.

, , true, const.

+3

, . A B .

public class A
{
    public bool Foo => true;
}

public class B
{
    public bool Foo { get; } = true;
}

, CIL-:

A a = new A();
B b = new B();

bool c;
c = a.Foo;
c = b.Foo;

:

            c = a.Foo;
00C50FB0  mov         ecx,dword ptr [ebp-40h]  
00C50FB3  cmp         dword ptr [ecx],ecx  
00C50FB5  call        00C50088  
00C50FBA  mov         dword ptr [ebp-54h],eax  
00C50FBD  movzx       eax,byte ptr [ebp-54h]  
00C50FC1  mov         dword ptr [ebp-48h],eax  
            c = b.Foo;
00C50FC4  mov         ecx,dword ptr [ebp-44h]  
00C50FC7  cmp         dword ptr [ecx],ecx  
00C50FC9  call        00C500A8  
00C50FCE  mov         dword ptr [ebp-58h],eax  
00C50FD1  movzx       eax,byte ptr [ebp-58h]  
00C50FD5  mov         dword ptr [ebp-48h],eax

, ( 3 → @Arvins). CIL- .

+2

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


All Articles