Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

properties

Is there a performance/memory usage difference between the two following property declarations, and should one be preferred?

public bool Foo => true;

public bool Foo { get; } = true;

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

like image 730
Callum Watkins Avatar asked Aug 06 '17 15:08

Callum Watkins


People also ask

Which statement apply to auto-implemented property?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is the point of auto properties?

properties allow your access to be polymorphic (inheritors can modify access if the property is virtual) if you so choose. auto-properties are nice when you're dealing with simple get/set operations. if you do more complicated operations inside your get / set, then you can't use the auto-property.

Can property be readonly in C#?

Create Readonly Property Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.

When property contains only get method then we get?

As discussed, if a property contains the only get accessor, then we will call it a read-only property. Following is the example of creating read-only properties in the c# programming language.


1 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 get 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;
        }
    }
}

So as @Fruchtzwerg mentioned both ways have the same way to return the value BUT the difference is in the implementation of getter methods since one return the value ture and the other return a field which has the value true.

Talking about performance and memory the first way seems to be better, but if you only need this property to be true I suggest to use const .

like image 186
Kahbazi Avatar answered Sep 28 '22 09:09

Kahbazi