C# Generic constraints to include value types AND strings

Brett Postin picture Brett Postin · Jan 5, 2012 · Viewed 31.6k times · Source

I'm trying to write an extension method on IEnumerable that will only apply to value types and strings.

public static string MyMethod<T>(this IEnumerable<T> source) where T : struct, string

However 'string' is not a valid constraint as it is a sealed class.

Is there any way to do this?

Edit:

What I'm actually trying to do is prepare a list of values for an "IN" clause in a dynamically constructed SQL.

I have lots of instances of code such as the following that I want to clean up:

sb.AppendLine(string.Format("AND value IN ({0})", string.Join(",", Values.Select(x => x.ToSQL()).ToArray())));

Where ToSQL() has code to handle SqlInjection.

Answer

KeithS picture KeithS · Jan 5, 2012

Maybe you could restrict to IConvertible types? All the system primitives that can be converted using these interface methods also implement the interface, so this restriction would require T to be one of the following:

  • Boolean
  • Byte
  • Char
  • DateTime
  • Decimal
  • Double
  • Int (16, 32 and 64-bit)
  • SByte
  • Single (float)
  • String
  • UInt (16, 32 and 64-bit)

If you have an IConvertible, chances are VERY good it's one of these types, as the IConvertible interface is such a pain to implement that it's rarely done for third-party types.

The main drawback is that without actually converting T to an instance of one of these types, all your method will know how to do is call the Object and IConvertible methods, or methods that take an Object or IConvertible. If you need something more (like the ability to add and/or concatenate using +), I think that simply setting up two methods, one generic to struct types and a second strongly-typed to strings, would be the best bet overall.