Skip to content

Instantly share code, notes, and snippets.

@pinkas
Created February 26, 2019 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinkas/aec5a3d688291c0cf2804ed8c1d66c96 to your computer and use it in GitHub Desktop.
Save pinkas/aec5a3d688291c0cf2804ed8c1d66c96 to your computer and use it in GitHub Desktop.
Will cache a collection of string based on a delegate you pass in - Useful when you need to do lots of string concatenation during gameplay
using System;
namespace SlugLib
{
public class StringCacher
{
public delegate string StringConstructor(int index);
private string[] strings;
private StringConstructor stringConstructor;
public int Capacity
{
get { return strings.Length; }
}
public StringCacher(int capacity, StringConstructor stringConstructor)
{
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException("Capacity must be greater than zero");
}
this.stringConstructor = stringConstructor;
strings = new string[capacity];
for (int i = 0; i < strings.Length; i++)
{
strings[i] = stringConstructor(i);
}
}
public string Get(int index)
{
if (strings != null && index >= 0 && index < Capacity - 1)
{
return strings[index];
}
else
{
return stringConstructor(index);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment