C# Generic constraints to include value types AND strings

Solution 1:

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.

Solution 2:

You need to define 2 separate methods:

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

Solution 3:

No, you can't. Generic constraints are always "AND"-ed, if you see what I mean (i.e. all constraints must be satisifed), so even if you were trying to use some unsealed class, this would still fail.

Why do you want to do this? Perhaps there's another approach which would work better.