简体   繁体   中英

Memory allocation for override properties of abstract classes

I have an abstract class where I define a bunch of properties. Will this cause each instance of a child class (which needs an override property) to allocate memory for this property? The reason I ask is that some child classes will need the property, and some never, but other classes do access the property of the abstract class.

And does it make a difference whether I override it like this:

public override int someProperty {get; set;}

Or like this (keeping the get and set methods empty on purpose, because maybe no memory is allocated for the associated field?)

    public override int someProperty
    {
        get
        {
        }
        set
        {
        }
    }

First question so I hope I'm asking everything correctly.

A property does not (necessarily) imply storage is allocated. Properties are just syntactic sugar around get and set methods. Unless you also have a field to store the data, they are just pairs of methods.

Example: If your base class has properties like this:

public virtual int SomeProperty { get { return 0; } { set { } }

Then no storage is allocated.

But if you use an auto-property:

public virtual int SomeProperty { get; set; }

Then there is an automatic backing field generated, for which storage is allocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM