Anti-C # generics restriction

Inspired by Phil Haack 's attempt at empty or empty coalescence , I'm trying to write a couple of extension methods for a string object, as well as on the IEnumerable<T> interface, to simplify null or emtpy ckecking. However, I ran into problems: when I try to call the string version of AsNullIsEmpty , the compiler treats my string as an IEnumerable<char> and, of course, gives the wrong return type.

Is there a way to set an “anti-restriction” in the IEnumerable version definition so that I can tell the compiler to use it when type T not string ? Something like

 public static IEnumerable<T> AsNullIfEmpty(this IEnumerable<T> items) where T !: string 

I know that I can just change the name of one of them, but I want to have the same name for consistency.

Update: It turns out that my problem with extension methods was solved in another way, by fixing a simple and silly error (I used str.IsNullOrEmpty() , the extension method on IEnumerable<T> , instead of string.IsNullOrEmpty(str) ...) , but since the question of anti-restrictions on generics remains interesting, I will not delete it.

+3
generics c # constraints
source share
1 answer

The only way to do this is to create an overload of this extension, which takes string as the this parameter.

 public static string AsNullIfEmpty(this string value) 

Doing this will result in a definitely typed version being considered a better overload match than the generic version.

As for your specific question ("Can I specify an" anti-restriction "for a generic type parameter?"), The answer will be no. However, you can get a very close value with the Obsolete attribute.

 [Obsolete("AsNullIfEmpty is not supported for strings.", true)] public static string AsNullIfEmpty(this string value) 

This will cause the compiler to report an error for this overload.

+8
source share

All Articles