Last active
May 4, 2020 05:20
-
-
Save gsscoder/e54d26ab5aa0f6cfb2fef85dc587dd9d to your computer and use it in GitHub Desktop.
Helper class that allows pattern matching on types
This file contains 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
// 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