How can I cache output of a method's parameters, so I don't have to create a new object when the input(s) are the same?

Calin Baenen - Feb 20 '21 - - Dev Community

I'm working on Janky in C#, and I have a JankyToken class. I'm gonna be making a lot of JankyTokens, so I need to know, how can I make a method (Create) of JankyToken that will cache it?

This is what I have so far:

// NOTE: `Type` is short for `JankyToken.Type` which is an
// enum that describes the token (e.g. `GT`, `LTEQ`, `ASS`, etc...).

/**
* @param type The type of token.
* @param value Additional data that describes custom tokens (e.g. Identifiers).
*/
public JankyToken Create(Type type, String value) {
    cache = /* Some method of retrieving the cached params */;
    if(cache != null) return cache;
    else {
        result = new JankyToken(type, value);
        /* Some method of caching the result */
        return cache;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks!
Cheers!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .