I have this extension method:
public static T Foo<T>(this Object current) where T : class, new()
{
...
}
Is it possible to exclude primitive types and IEnumerable interface from "this Object current"?
Editet My question is not a duplicate, because in suggested question problem is in collision of parameters between overload methods. Author asked, is it possible to exclude String type from one of methods to give abbility for another method to pick it. And helpful answer for that question is not helpful for me
No. You cannot. There is no generic type constraint available for such things. An option could be to specify a method which you mark Obsolete
:
[Obsolete("Do not use with IEnumerable!", true)]
public static T Foo<T>(this IEnumerable current) where T : class, new()
{
...
}
You do understand the list would get endless. Another option would be a Roslyn code analyzer which checks your code for disallowed combinations, but that might be overkill.
Patrick Hofman allready gave the correct answer, but i want to offer another possibility to deal with that problem
As Evk allready stated in his comment.
Depending on how many types you want to allow, you could explicitly allow these types.
I don't really like the Feeling of adding obsolete Tags to Enforce certain types on Genericmethods.
Warning: Do not use the following approach!
You could must not check for the type and throw an exception.
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="current">Dont throw in IENumerables !</param>
/// <returns></returns>
public static T Foo<T>(this Object current) where T : class, new() {
if (current is IEnumerable) {
throw new NotSupportedException($"Type {current.GetType()} is not supported!");
}
//...
}
Why is this a bad approach? -> This could result in crashing your application.
Why is Patricks approach better? -> His approach results in a compiler warning/error, which is better than having an Application crash in production.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With