Does Properties increase memory size of Instances?

后端 未结 5 566
天涯浪人
天涯浪人 2021-01-19 10:30

This is probably a stupid question, but does object Properties occupy any memory per instance?

As I\'ve understand it when you instantiate an object each value field

相关标签:
5条回答
  • 2021-01-19 11:12

    No, properties are just syntactic sugar for getter and setter methods. Only the backing fields occupy memory. If you have no backing fields, you will have no per-instance memory usage.

    0 讨论(0)
  • 2021-01-19 11:18

    Properties are tranlated into two (or just one in case You provided only a getter or perhaps a setter) method that is

    public int MyProp
    {
        get { return 1; }
        set { myField = value; }
    }
    

    is translated during compilation (probably Eric Lipper will correct me on this, becasue maybe it is during the preprocessing phase or sth) into methods

    public int Get_MyProp();
    public int Set_MyProp(int value);
    

    all in all they carry no other overhead other than just to additional methods inluced in the object

    0 讨论(0)
  • 2021-01-19 11:19

    If you look at a compiled C# class through for instance reflector you will see that the compiler actually translates the properties into get and set methods, auto properties are translated into get and set methods with a backing field, so the field will take up as much room as a regular field

    0 讨论(0)
  • 2021-01-19 11:33

    Properties are just like ordinary methods in that respect.

    The code needs to be stored somewhere (once per Type) and any fields that are used (Auto properties!) need to be stored per instance. Local variables will also take up some memory.

    0 讨论(0)
  • 2021-01-19 11:34

    Straight from Apress Illustrated C#

    Unlike a field, however, a property is a function member.
    - It does not allocate memory for data storage!
    
    0 讨论(0)
提交回复
热议问题