Skip to content

Instantly share code, notes, and snippets.

@rje
Created October 21, 2014 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rje/bd8fb129aacda2e5601c to your computer and use it in GitHub Desktop.
Save rje/bd8fb129aacda2e5601c to your computer and use it in GitHub Desktop.
Generic function to convert a string into an enum type
public T ReadEnum<T>(string tok)
{
if(typeof(T).IsEnum == false)
{
Debug.LogWarning("Generic type " + typeof(T).Name + " passed to ReadEnum<T> is not an enum type, returning default value");
return default(T);
}
T toReturn = default(T);
try
{
toReturn = (T)Enum.Parse(typeof(T), tok);
}
catch (Exception e)
{
Debug.LogWarning("String " + tok + " is not a valid type in enum " + typeof(T).Name + ", returning default value");
}
return toReturn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment