Skip to content

Instantly share code, notes, and snippets.

@freakingawesome
Created August 12, 2015 10:31
Show Gist options
  • Save freakingawesome/5d94d14c1110aa174343 to your computer and use it in GitHub Desktop.
Save freakingawesome/5d94d14c1110aa174343 to your computer and use it in GitHub Desktop.
public static class ArgApplier
{
static T ChangeType<T>(object[] vals, int index)
{
if (vals == null || vals.Length <= index)
{
return default(T);
}
var val = vals[index];
if (object.ReferenceEquals(val, null) || val == null || (val as string == "" && typeof(T) != typeof(string)))
{
return default(T);
}
var underlying = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
try
{
return (T)Convert.ChangeType(val, underlying);
}
catch (Exception x)
{
throw new Exception("Could not convert value to " + typeof(T).FullName + ": " + val, x);
}
}
public static void Apply<T0>(object[] args, Action<T0> action)
{
action(
ChangeType<T0>(args, 0)
);
}
public static void Apply<T0, T1>(object[] args, Action<T0, T1> action)
{
action(
ChangeType<T0>(args, 0),
ChangeType<T1>(args, 1)
);
}
public static void Apply<T0, T1, T2>(object[] args, Action<T0, T1, T2> action)
{
action(
ChangeType<T0>(args, 0),
ChangeType<T1>(args, 1),
ChangeType<T2>(args, 2)
);
}
public static void Apply<T0, T1, T2, T3>(object[] args, Action<T0, T1, T2, T3> action)
{
action(
ChangeType<T0>(args, 0),
ChangeType<T1>(args, 1),
ChangeType<T2>(args, 2),
ChangeType<T3>(args, 3)
);
}
public static void Apply<T0, T1, T2, T3, T4>(object[] args, Action<T0, T1, T2, T3, T4> action)
{
action(
ChangeType<T0>(args, 0),
ChangeType<T1>(args, 1),
ChangeType<T2>(args, 2),
ChangeType<T3>(args, 3),
ChangeType<T4>(args, 4)
);
}
public static void Apply<T0, T1, T2, T3, T4, T5>(object[] args, Action<T0, T1, T2, T3, T4, T5> action)
{
action(
ChangeType<T0>(args, 0),
ChangeType<T1>(args, 1),
ChangeType<T2>(args, 2),
ChangeType<T3>(args, 3),
ChangeType<T4>(args, 4),
ChangeType<T5>(args, 5)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment