Created
February 26, 2019 21:59
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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