Does a property take up space on the object?


I was reading a query about properties and saw that it is one or two methods at one time.

Is there any additional cost in memory and processing in using it? If you do not use the code can you get more optimized?

asked by anonymous 11.05.2017 / 16:11

1 answer


The property itself is a method or a pair of methods get and set . Then like any method a memory space is occupied for the method code. It is a very small thing and can practically be disregarded.

Like every method there is a code execution and there is a processing cost that depends on what will be executed. Even an empty method has some cost , if not optimized.

So if you're just assigning or taking a value it has an overhead compared to doing it right in the field.

If you want to know if it occupies a space in the instance, the property itself does not occupy. But it is very common for it to access a field, in fact it may even encapsulate that field. The field space creates a cost on the object, but if the property does not have a bound field there is no cost.

Just notice that this

public int prop { get; set; }

By default there is a field associated with it that does not appear in the code, so this field will take up space. In this example as it is a int will occupy 4 bytes.


public bool prop { get => status > 0; }

does not have a direct field, so it does not take any more. Of course this field status is a field that will occupy a space, but it is not bound to the prop property, this property does not create overhead in the object.

Night that the property can make maintenance and versioning easier, but it imposes a processing cost however simple it may be. In general it is good to use it, but if you need a lot of the best possible performance the access to the direct field can be better, so do not call any extra code. Have a question to better understand the advantage of using a property to encapsulate a field .

using static System.Console;

public class Program {
    public static void Main() {
        var objeto = new Classe(1);

public class Classe {
    public Classe(int x) => status = x;
    private int status; //aqui ocupa 4 bytes
    public bool IsFree { get => status > 0; } //aqui nada ocupa na instância
    public int Id { get; } = 0; //aqui ocupará 4 bytes porque tem um campo implícito

See running on .NET Fiddle . And on the Coding Ground. Also put it on GitHub for future reference .

11.05.2017 / 16:28