Search code examples
c#stringgenericsconstraintsvalue-type

C# Generic constraints to include value types AND strings


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.


Solution

  • 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.