Question

I have a question regarding the memory use classes used as properties in C#. Looking at the code below, will memory be allocated to the "mySubClass"-property of a baseClass object before "InitSubClass()" is run?

If so, I guess it will be fairly little as the SubClass.MyData disctionary isn't initialised, but still more than nothing... Is this at all a decent way of "expanding" the base class (without deriving additional classes)? I am trying to keep a fairly basic baseClass. For certain operations, however, I need additional properties, which I only want to exist for a short duration and not take up memory otherwise.

Many thanks for pointers in the right direction!

    class BaseClass
    {

    private SubClass mySubClass;

    public SubClass MySubClass
    {
    get
    {
    return mySubClass;
    }
    }

    void InitSubClass()
    {
    mySubClass = new SubClass(this);
    }

    }

    class SubClass
    {

    BaseClass mybaseClass
    {
    get; set;
    }

    //a lot, and potentially fairly heavy properties which I only need for a short duration, e.g. 
    Disctionary<int,object MyData;

    public Subclass(BaseClass myBaseClass_in)
    {
    mybaseClass = myBalseClass_in;
    }


    }
Was it helpful?

Solution

No, will be allocated only a pointer to nothing (null pointer).

This private SubClass mySubClass; points to nothing so == null.

Only at the moment you call

void InitSubClass()
{
  mySubClass = new SubClass(this);
}

actual memory for that instance will be allocated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top