I have a the following generic methods:
public static string Glue(string prefix, string value)
{
return String.Format("{0}={1}&", prefix, value);
}
public static string Format<T>(string prefix, T obj) where T : struct
{
return Glue(prefix, (obj).ToString()); ;
}
public static string Format<T>(string prefix, List<T> obj) where T : struct
{
return String.Join("",obj.Select(e => Glue(prefix, e.ToString())).ToArray());
}
Now I’d like to call them with a parameter that comes in as an object and could be a variety of types.
I started writing some code and it started looking like it’s going to have a very long if/else sequence:
// type of value is object, and newPrefix is string
if (value is int)
{
return Format(newPrefix, (int)(value));
}
else if (value is double)
{
return Format(newPrefix, (double)value);
}
...
Is there a way of avoiding this long sequence of if/else?
As stated there’s not much of a way to make this simpler. The
Formatmethod is constrained to only taking value types (structs) which is easy to detect at the call siteBut there’s no way to then to make the
Formatcall happy as you can’t provide theTtype.What you can do here is change
Formatslightly. The method call only uses theToStringmethod which is available on all types. You could remove thestructconstraint and then call it with the value already inobjectform