Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active May 4, 2020 05:20
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 gsscoder/e54d26ab5aa0f6cfb2fef85dc587dd9d to your computer and use it in GitHub Desktop.
Save gsscoder/e54d26ab5aa0f6cfb2fef85dc587dd9d to your computer and use it in GitHub Desktop.
Helper class that allows pattern matching on types
// Based on: https://docs.microsoft.com/en-gb/archive/blogs/jaredpar/switching-on-types
// Example:
// TypeSwitch.Do(propertyInfo.PropertyType,
// TypeSwitch.Case<bool>(() => value = property.Value.GetBoolean()),
// TypeSwitch.Case<int>(() => value = property.Value.GetInt32()),
// TypeSwitch.Case<long>(() => value = property.Value.GetInt64()),
// TypeSwitch.Case<double>(() => value = property.Value.GetDouble()),
// TypeSwitch.Case<string>(() => value = property.Value.GetString()),
// TypeSwitch.Default(() => throw new InvalidOperationException("Type is not supported.")));
using System;
static class TypeSwitch
{
public class CaseInfo
{
public bool IsDefault { get; set; }
public Type Target { get; set; }
public Action Action { get; set; }
}
public static void Do(Type type, params CaseInfo[] cases)
{
foreach (var entry in cases) {
if (entry.IsDefault || type == entry.Target) {
entry.Action();
break;
}
}
}
public static CaseInfo Case<T>(Action action)
{
return new CaseInfo() {
Action = action,
Target = typeof(T)
};
}
public static CaseInfo Default(Action action)
{
return new CaseInfo() {
Action = action,
IsDefault = true
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment