Roci
Roci

Reputation: 123

Does a property with an empty setter take up memory space?

Of the three properties below, does only BarProp require the 4 bytes memory per class instance?

class Foo
{
    int BarEmptySet { get { return 0; } set { } }
    int BarNoSet { get { return 0; } }
    int BarProp { get; set; }
}

Upvotes: 1

Views: 744

Answers (2)

Saeb Amini
Saeb Amini

Reputation: 24410

The compiler only generates a backing field for Auto-Implemented Properties (e.g. BarProp). When you provide custom get/set implementations (e.g. BarEmptySet and BarNoSet) a backing field isn't automatically generated so they won't contribute to the object's memory footprint by themselves.

This can be easily verified by looking at the generated IL:

BarEmptySet:

// getter
IL_0000:  nop         
IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     
IL_0003:  br.s        IL_0005
IL_0005:  ldloc.0     
IL_0006:  ret         

// setter
IL_0000:  nop         
IL_0001:  ret  

BarNoSet:

// getter
IL_0000:  nop         
IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     
IL_0003:  br.s        IL_0005
IL_0005:  ldloc.0     
IL_0006:  ret   

// no setter is generated

BarProp:

// getter
IL_0000:  ldarg.0     
IL_0001:  ldfld       UserQuery+Foo.<BarProp>k__BackingField
IL_0006:  ret         

// setter
IL_0000:  ldarg.0     
IL_0001:  ldarg.1     
IL_0002:  stfld       UserQuery+Foo.<BarProp>k__BackingField
IL_0007:  ret    

As you can see, only BarProp uses stfld to set a backing field and ldfld to return the backing field's value. Others just use the literal 0.

Upvotes: 5

eocron
eocron

Reputation: 7536

As far as Im conserned, properties are in fact "sugar" which wraps fields of class in two methods: getter and setter by default.

But, it also can describe non-variable values, such as constants, functions and etc. So in your case it will instantiate only getter/setter function without background fields for all of your class instances, but the last one will perform its "default" duty - create hidden field which takes memory per class.

Upvotes: 1

Related Questions