David Torrey
David Torrey

Reputation: 1342

C# Object Memory Representation

I have a base class:

abstract class foo(){
     abstract dynamic DefaultValue { get; }
}

I'd like to be able to inherit from this for multiple objects and set a default value:

class bar : foo{
     override dynamic DefaultValue { get { return 0.0f; } }
}

How would this be represented in memory? would each object store its own "DefaultValue", or would it only be stored in memory once with each object referenciong it?

Upvotes: 1

Views: 331

Answers (3)

meJustAndrew
meJustAndrew

Reputation: 6603

It will make sense to create a method for the DefaultValue something as :

GetDefaultValue(){ return 0.0f; }

As long as methods do not take additional memory per object. On the other side, declaring auto-properties, will always create additional private fields to hold the data, and this will be added on each object you create, so it's not memory efficient.

It is realy a confuzing situation, as looking at this question will see that an auto property will take additional space.

But if you look at Jon Skeet's answer right here, he is saying that

The size of an individual object is not affected by the number of properties, methods, events etc.

In this case they may have the same effect, you can test it yourself against a large range of objects, but it is more surely to make a method, as it is referenced by all the objects within the method table.

Upvotes: 1

Eric Linde
Eric Linde

Reputation: 191

Short answer - there will be no extra memory per object to store a default value A read only property with only a return statement will compile to a method

get_DefaultValue()

Upvotes: 1

Rahul
Rahul

Reputation: 77846

If that's the case, then I would say make it a generic method like

public T GetTypedefaultvalue<T>()
{
  return default(T);
}

You can then call it as

GetTypedefaultvalue<double>();

(OR)

GetTypedefaultvalue<string>();

Upvotes: 0

Related Questions