Home > Software engineering >  How to use cache when constructor is called
How to use cache when constructor is called

Time:11-30

I have a class MyClass and since it takes some time to create an instance of this class, I want to use cache. My idea was to create the following constructor:

public MyClass(string name, int value)
    {
        if (Cache.MyClassObjects.ContainsKey(name))
            this = Cache.MyClassObjects[name]
        else:
            this.Name = name;
            this.Value = value;
    }

The problem is that I can't perform this line this = Cache.MyClassObjects[name]. For me the above is the most natural solution - user called the constructor and if the object with the same name and value already exsists - return that object. Another solution would be to implement a static function inside my class but first I would like to know why this doesnt work.

CodePudding user response:

Constructor always returns new instance by design. Runtime allocates memory for that fresh instance (for reference types at least), and then your constructor runs. Then fresh instance is returned to the caller.

It can't allow you to return completely separate existing instance and throw away the fresh one it already allocated memory for. Well with some efforts language designers might have been able to implement that syntax, but there is absolutely no reason to waste time on that - you already know how to do it with the current version of the language, just use static method.

  •  Tags:  
  • c#
  • Related