Roland Mai
Roland Mai

Reputation: 31097

Dealing with object parameters and generics

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?

Upvotes: 1

Views: 91

Answers (1)

JaredPar
JaredPar

Reputation: 755259

As stated there's not much of a way to make this simpler. The Format method is constrained to only taking value types (structs) which is easy to detect at the call site

if (value.GetType().IsValueType) {
  // it's a struct
}

But there's no way to then to make the Format call happy as you can't provide the T type.

What you can do here is change Format slightly. The method call only uses the ToString method which is available on all types. You could remove the struct constraint and then call it with the value already in object form

public static string Format(string prefix, object obj) {
    return Glue(prefix, obj.ToString()); ;
}

if (value.GetType().IsValueType) {
  Format(newPrefix, value);
}

Upvotes: 2

Related Questions