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.
generics c # constraints
Tomas lycken
source share