In a similar situation I ended up using a generic helper to make intent clearer. I did have <T>
type available but not the C#9 default (T) switch { string[] => ...}
syntax.
This solution seems to be handling nullables like DateTime?
correctly.
static object Convert(string str, Type type)
=> type switch {
_ when Match<string>(type) => str,
_ when Match<string[]>(type) => str.Split(new[] { ',', ';' }),
_ => TypeDescriptor.GetConverter(type).ConvertFromString(str)
};
static bool Match<T>(Type t) => typeof(T) == t;
For my <T>
available case it became something like:
static object Convert<T>(string str)
=> type switch
{
_ when Match<string, T>() => str,
_ when Match<string[], T>() => str.Split(new[] { ',', ';' }),
_ => TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(str)
};
static bool Match<TA, TB>() => typeof(TA) == typeof(TB);
edit:
One can shorten the syntax a bit with an extension method:
...
public static bool Is<T>(this System.Type type) => type == typeof(T);
...
static object Convert(string str, Type type)
=> type switch {
_ when type.Is<string>() => str,
_ when type.Is<string[]>() => str.Split(new[] { ',', ';' }),
_ => TypeDescriptor.GetConverter(type).ConvertFromString(str)
};
_ when type == stringType => str,
which may read slightly better? – Clotildeobject
? – Clotilde